如何在gridview单元格中动态添加下拉列表

时间:2013-07-26 20:46:17

标签: c# asp.net gridview drop-down-menu

我有一个网格视图,如果数据库为特定列返回null,我想插入一个从数据库填充的下拉列表。

以下是我必须确定该列为null且代码正常的代码。

protected void viewThemeTypeAssociationsGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells[1].Text == " ")
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         //fill current rows cell with a dropdown list
     }
}

此外,一旦我填充了该行,当有多个版本时,如何知道具体使用哪个下拉列表?

1 个答案:

答案 0 :(得分:3)

使可能填充的下拉列表成为行模板的一部分。默认情况下,使下拉列表不可见,然后只有使用数据库中的数据填充它才能使其可见。

在没有看到您的代码的情况下,我猜您正在使用TemplateField来在网格视图中定义列,如下所示:

<asp:GridView id="viewThemeTypeAssociationsGridView" ruant="server" OnRowDataBound="viewThemeTypeAssociationsGridView_OnRowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
            <ItemTemplate>
                <asp:DropDownList id="DropDownList1" runat="server" Visible="False">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

现在,对于网格视图中的每一行,当您处于RowDataBound事件时,您可以找到下拉列表,如下所示:

if (e.Row.RowType == DataControlRowType.DataRow)
{
     // Find the drop down list by name
     DropDownList theDropDownList = (DropDownList)e.Row.FindControl("DropDownList1");

     // Go get data from database and populate the drop down list

     // Change visibility of drop down list here
     theDropDownList.Visible = true;
}

注意:在网格视图的每一行中都会有一个名为DropDownList1的控件,FindControl()方法会为您正在使用的行获取“正确的”。