Can't find dropdown list in RowDataBound event

两盒软妹~` 提交于 2019-12-25 02:39:05

问题


I'm following this example http://www.codeproject.com/KB/webforms/Editable_GridView.aspx to build an editable GridView control. I have this code in my 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> 

Now, I'm trying to fill the dropdown in the EditItemTemplate with some dynamic values just as the example says, in the RowDataBound Event of the grid. But when I do this, the FindControl method always returns 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

If I can't find the Dropdown I can't load the values in it and when I'm going to edit de entry it will be empty.

Can someone help me?

Thank you (:


回答1:


Please use the RowEditing-Event, as your DropDownList should only be shown when clicking Edit. But first, you have to bind the GridView newly as the GridView now needs to render different controls for the edit row:

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:


The FindControl always return null because when your in the RowDataBound event you can get the label only.

If you want to fill the DropDownList when you click the edit button on the grid, then you have to use the GridViewRowEditing event.




回答3:


In the RowDataBound event, simply add the following conditional:

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


来源:https://stackoverflow.com/questions/8573260/cant-find-dropdown-list-in-rowdatabound-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!