【问题标题】:How to dynamically add drop down lists inside gridview cells如何在gridview单元格内动态添加下拉列表
【发布时间】:2013-07-26 20:46:17
【问题描述】:

我有一个网格视图,如果数据库为特定列返回 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
     }
}

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

【问题讨论】:

  • 调用 findControl 来查找下拉菜单并向其添加文本和值。那只是理论。这里有人问了类似的问题。 stackoverflow.com/questions/7305905/…
  • 除此之外:将e.Row.RowType 检查放在e.Row.Cells 检查之外——这样会更有效率。

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


【解决方案1】:

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

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

<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() 方法会为您正在使用的行获取“正确的”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 2023-03-15
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    相关资源
    最近更新 更多