【问题标题】:Can't find dropdown list in RowDataBound event在 RowDataBound 事件中找不到下拉列表
【发布时间】:2012-01-24 06:53:54
【问题描述】:

我正在按照这个示例http://www.codeproject.com/KB/webforms/Editable_GridView.aspx 构建一个可编辑的 GridView 控件。 我的 GridView 中有这段代码:

<asp:TemplateField HeaderText="Negócio">
<ItemTemplate> 
    <asp:Label ID="lblNegocio" runat="server" Text='<%# Eval("Negocio") %>'></asp:Label> 
</ItemTemplate> 
<EditItemTemplate> 
    <asp:DropDownList ID="ddlNegocio" runat="server" /> 
</EditItemTemplate> 
<FooterTemplate> 
    <asp:DropDownList ID="ddlNewNegocio" runat="server" />
</FooterTemplate> 

现在,正如示例所述,我正在尝试在网格的 RowDataBound 事件中使用一些动态值填充 EditItemTemplate 中的下拉列表。但是当我这样做时,FindControl 方法总是返回 Nothing:

Protected Sub gdvRegraRotationDefault_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gdvRegraRotationDefault.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
    Dim ddlNegocio As DropDownList = e.Row.FindControl("ddlNegocio")
End If

结束子

如果我找不到下拉列表,我将无法加载其中的值,当我要编辑 de 条目时,它将为空。

有人可以帮我吗?

谢谢(:

【问题讨论】:

    标签: asp.net vb.net gridview


    【解决方案1】:

    请使用 RowEditing-Event,因为您的 DropDownList 仅应在单击编辑时显示。 但首先,您必须重新绑定 GridView,因为 GridView 现在需要为编辑行呈现不同的控件:

    protected void gdvRegraRotationDefault_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gdvRegraRotationDefault.EditIndex = e.NewEditIndex;
        gdvRegraRotationDefault.DataBind();
    
        GridViewRow row = gdvRegraRotationDefault.Rows[e.NewEditIndex];
        DropDownList ddl = row.FindControl("ddlNegocio") as DropDownList;
    
        //now do databinding for DropDownList
    }
    

    【讨论】:

      【解决方案2】:

      FindControl 总是返回 null,因为当您在 RowDataBound 事件中时,您只能获取标签。

      如果要在单击网格上的编辑按钮时填充 DropDownList,则必须使用 GridViewRowEditing 事件。

      【讨论】:

      • 对,但在这种情况下,我不能使用 FindControl 方法,因为类 GridViewEditEventArgs 无法访问 Row 属性。我该怎么做?
      • 你有两个选择,要么将发件人解析为 GridViewRow,要么使用 e.NewEditIndex,它是正在编辑的行的索引,然后你在该行中找到控件。
      • Dim row As GridViewRow = gdvRegraRotationDefault.Rows(e.NewEditIndex) Dim ddlNegocio As DropDownList = row.FindControl("ddlNegocio") //仍然返回 Nothing ):
      • 正如 Jan-Frederik Carl 所说,您必须执行 GridView.DataBind(),然后才能访问您的控件。
      【解决方案3】:

      在 RowDataBound 事件中,只需添加以下条件:

      if (myGridView.EditIndex == e.Row.RowIndex)
      {
           //do work
      }
      

      【讨论】:

      • 嗯,我想你不理解我的问题,这对我没有帮助。还是谢谢。
      • 是的,但是 Jan-Frederik Carl 和 yahya kh 已经帮助我解决了我的问题。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2014-10-12
      • 2021-01-23
      相关资源
      最近更新 更多