【问题标题】:Binding dropdown list in a gridview edit item template在gridview编辑项模板中绑定下拉列表
【发布时间】:2009-03-07 08:29:32
【问题描述】:

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

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

也报错

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

【问题讨论】:

  • 您得到的异常与您发布的代码无关。您的例外是关于您在页面回发之间添加或删除的控件。

标签: c# .net asp.net gridview


【解决方案1】:

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

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

然后找到您的控件进行此调用:

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

【讨论】:

  • 我试过了,但还没有解决。当我点击编辑按钮时,它会抛出错误加载视图状态失败。正在加载视图状态的控件树必须与之前请求期间用于保存视图状态的控件树匹配。
  • 好的,您能否提供一个简短、完整的示例来演示该问题?如果您将代码代码文件放在某个地方,我可能会提供帮助。
【解决方案2】:
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            
    }
}

【讨论】:

    【解决方案3】:
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多