【问题标题】:Add and find Dropdownlist at Runtime inside GridView在 GridView 内的 Runtime 添加和查找 Dropdownlist
【发布时间】:2015-05-04 06:21:41
【问题描述】:

在我的 asp.net 应用程序中,我使用了 Gridview 控件,我必须在运行时为每个单元格添加 Dropdownlist。我能够成功绑定。 下面是我在行数据绑定事件中的代码,

foreach (GridViewRow row in gdvLocation.Rows) {
    if (row.RowType == DataControlRowType.DataRow) {
        for (int i = 1; i < row.Cells.Count; i++) {
            var dlRouteType = new DropDownList();
            dlRouteType.ID = "ddlRouteType";
            dlRouteType.DataSource = GetRouteTypeList();
            dlRouteType.DataTextField = "RouteType";
            dlRouteType.DataValueField = "Id";
            dlRouteType.DataBind();
            row.Cells[i].Controls.Add(dlRouteType);
        }
    }
}

我的页面中有一个按钮,它具有将数据保存到数据库的功能。在保存数据时,我必须传递我在运行时添加的 Dropdownlist 中的值。单击按钮时,我正在编写以下代码以从下拉列表中获取数据,

var ddlDropDown = (DropDownList)row.Cells[i].FindControl("ddlRouteType");

但我在 ddlDropDown 对象中得到空值。我什至在 aspx 页面中添加了更新面板。欢迎提出任何建议。 提前致谢 桑吉萨

【问题讨论】:

  • 您可能正在查看错误的单元格,尝试使用 row.FindControl("ddlRouteType");还要确保不要在回发时重新绑定 gridview。
  • 你将 ddl 添加到每一行的每一列?
  • 你应该发布整个按钮点击处理程序

标签: c# asp.net gridview


【解决方案1】:

您的代码中有这些错误

  1. RowDataBound 已经遍历了每一行,因此您无需在顶部写上 foreach
  2. 您从索引 1 开始迭代,索引从零开始。所以从零开始。
  3. DropDownList ID 必须是唯一的,所以最好写类似dlRouteType.ID = "ddlRouteType_" + i;

代码应该是,

protected void gdvLocation_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //removed the foreach loop
    var row = e.Row;
    if (row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < row.Cells.Count; i++) //changed index
        {
            var dlRouteType = new DropDownList();
            dlRouteType.ID = "ddlRouteType_" + i; //gave unique id
            dlRouteType.DataSource = GetRouteTypeList();
            dlRouteType.DataTextField = "RouteType";
            dlRouteType.DataValueField = "Id";
            dlRouteType.DataBind();
            row.Cells[i].Controls.Add(dlRouteType);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多