在运行时在 GridView 中添加和查找下拉列表

Add and find Dropdownlist at Runtime inside GridView

在我的 asp.net 应用程序中,我使用了 Gridview 控件,我必须在运行时为每个我能够成功绑定的 cell.Which 添加 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 对象中得到了 null。我什至在 aspx 页面中添加了更新面板。欢迎提出任何建议。 提前致谢 桑吉萨

您的代码中存在这些错误

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