Set the current value of gridview DDL on EditItemT

2020-03-31 09:02发布

问题:

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>

回答1:

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();
        }
    }
}


回答2:

I ended up using:

 SelectedValue='<%# Bind("myID") %>' 

to display the current record in the ddl.