C# gridview 编辑项模板中的绑定下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/621536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:38:27  来源:igfitidea点击:

Binding dropdown list in a gridview edit item template

c#.netasp.netgridview

提问by

i can bind the dropdownlist in the edit item template. The drop down list is having null values.

我可以在编辑项模板中绑定下拉列表。下拉列表具有空值。

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e) 
{   
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)    
  {        
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");    
  }
}

also getting an error

也收到错误

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

无法加载视图状态。正在加载视图状态的控件树必须与在前一个请求期间用于保存视图状态的控件树匹配。例如,动态添加控件时,回发期间添加的控件必须与初始请求期间添加的控件的类型和位置相匹配。

回答by ilivewithian

I had problems with find control, in the end I used a little bit of recursion to find the control:

我在查找控件时遇到了问题,最后我使用了一点递归来查找控件:

private Control FindControlRecursive(Control root, string id) 
{ 
     if (root.ID == id)
    { 
         return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
         Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

     return null; 
}

Then to find your control make this call:

然后要找到您的控件,请拨打以下电话:

drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");

回答by bahith

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drpBuildServers;

        drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;

        if (drpBuildServers != null)
            // Write your code here            
    }
}

回答by Test

Its a solution for me:

它对我来说是一个解决方案:

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drpBuildServers;

        drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;

        if (drpBuildServers != null)
            // Write your code here            
    }
}