How do I set the selected value in a gridview dropdownlist to what is in the current record like I currently do for a text box.
I am hoping the user can look at the current values and decide if they need to be changed -- this is what I use for a textbox:
<asp:TemplateField HeaderText="Other Notes" SortExpression="Other Notes" HeaderStyle-Wrap="false">
<edititemtemplate>
<asp:TextBox ID="txtOtherNotes" runat="server" Text='<%# Eval("[Other Notes]") %>' DataTextField="Other Notes" DataValueField="Other Notes"></asp:TextBox>
</edititemtemplate>
<itemtemplate>
<asp:Label runat="server" Text='<%# Bind("[Other Notes]") %>' ID="lblOtherNotes"></asp:Label>
</itemtemplate>
</asp:TemplateField>
You will need to use the OnRowDataBound
event for that.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if the row is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
//find the dropdownlist in the row using findcontrol
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList");
//fill the dropdownlist from code behind if needed
ddl.DataSource = source;
ddl.DataTextField = "key";
ddl.DataValueField = "valee";
ddl.DataBind();
//cast the dataitem back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//set the correct listitem as selected
ddl.SelectedValue = row["myValue"].ToString();
}
}
}
I ended up using:
SelectedValue='<%# Bind("myID") %>'
to display the current record in the ddl.