将下拉列表绑定到编辑时gridview上的ItemTemplate中已显示的值

时间:2013-03-18 09:44:27

标签: asp.net c#-4.0

我必须将我的下拉列表值绑定到我的编辑模板。下面是我的下拉列表的代码。

 protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //Check if this is our Blank Row being databound, if so make the row invisible
    if (e.Row.RowType == DataControlRowType.DataRow)
    {

        if (((DataRowView)e.Row.DataItem)["CertificateNo"].ToString() == String.Empty) e.Row.Visible = false;
        //Check if is in edit mode
       if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DropDownList DropDownListStatus = (DropDownList)e.Row.FindControl("DropDownListStatus");
            //Bind status data to dropdownlist
            DropDownListStatus.DataTextField = "Status";
            DropDownListStatus.DataValueField = "Status";
            DropDownListStatus.DataSource = RetrieveStatus();
            DropDownListStatus.DataBind();
            DataRowView dr = e.Row.DataItem as DataRowView;
            DropDownListStatus.SelectedValue = dr["Status"].ToString();
           }


    }
}

private DataTable RetrieveStatus()
{
    //fetch the connection string from web.config
    string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    //SQL statement to fetch entries from products
    string sql = @"Select distinct Status from cpd_certificates";
    DataTable dtStatus = new DataTable();
    //Open SQL Connection
    using (SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();
        //Initialize command object
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            //Fill the result set
            adapter.Fill(dtStatus);
        }
    }
    return dtStatus;
}

上面的代码填充了我的下拉列表。但是,当我单击编辑时,我的下拉列表未填充。 这是我的下拉列表代码:

<asp:TemplateField HeaderText="Status" SortExpression="Status">
                                            <ItemTemplate><%# Eval("Status")%></ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:DropDownList ID="DropDownListStatus" runat="server">
                                                </asp:DropDownList>

                                            </EditItemTemplate>
                                            <FooterTemplate>
                                                <asp:DropDownList ID="DropDownListStatus" runat="server" >

                                                </asp:DropDownList>

                                            </FooterTemplate>
                                        </asp:TemplateField>

1 个答案:

答案 0 :(得分:0)

快速浏览一下代码,可以看出按顺序将值分配给下拉列表时出错。首先将数据源分配到下拉列表,然后在分配数据源后分配datavalue-field和datatext-field属性。 / p>

 DropDownListStatus.DataSource = RetrieveStatus();
 DropDownListStatus.DataTextField = "Status";
 DropDownListStatus.DataValueField = "Status";