在RowDataBound事件中找不到下拉列表

时间:2011-12-20 09:28:00

标签: asp.net vb.net gridview

我正在关注此示例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> 

现在,我正在尝试使用一些动态值来填充EditItemTemplate中的下拉列表,就像示例所示,在网格的RowDataBound事件中。但是当我这样做时,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

End Sub

如果我找不到Dropdown,我无法加载其中的值,当我要编辑de entry时,它将为空。

有人可以帮助我吗?

谢谢(:

3 个答案:

答案 0 :(得分:3)

请使用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
}

答案 1 :(得分:2)

FindControl始终返回null,因为当您在RowDataBound事件中时,您只能获得标签。

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

答案 2 :(得分:0)

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

if (myGridView.EditIndex == e.Row.RowIndex)
{
     //do work
}
相关问题