在EditItemTemplate上设置gridview DDL的当前值

时间:2017-02-27 14:02:52

标签: c# asp.net gridview

如何将gridview下拉列表中的选定值设置为当前记录中的内容,就像我目前为文本框所做的那样。

我希望用户可以查看当前值并确定是否需要更改 - 这就是我用于文本框的内容:

<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>

2 个答案:

答案 0 :(得分:1)

您需要使用OnRowDataBound事件。

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

答案 1 :(得分:0)

我最终使用了:

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

显示ddl中的当前记录。