Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 82.8k

finding from code-behind some object in gridview

Jul 26 2022 8:52 AM

Hi

There is a gridview with a hiddenfield and a dropdownlist in templates. I have to find them from code-behind. I have the solution but don't understand everything.

1) from event GridView1_RowDataBound: why does this not work: sv = sender.FindControl("HiddenField1") ?

2) from event d2_SelectedIndexChanged: why do I have to use 'sender' here like  dd2 = sender.FindControl("HiddenField1") and not simply dd2 = FindControl("HiddenField1") ?

'Sender' refers to the object which raised the event, but this is as if 'HiddenField1' was inside the dropdownlist.

Thanks

<Columns>
<asp:TemplateField HeaderText="answer">
            <EditItemTemplate>
            <asp:HiddenField ID="HiddenField1" runat="server"  Value='<%# Bind("answer") %>' />
            <asp:DropDownList ID="dd2" runat="server" Width="260px" onselectedindexchanged="dd2_SelectedIndexChanged">
            </asp:DropDownList>
             </EditItemTemplate>
              <ItemTemplate>
              <asp:Label ID="Label2" runat="server" Text='<%# Bind("answer") %>'></asp:Label>
              </ItemTemplate>
</asp:TemplateField>
</Columns>

-----
Friend sv As HiddenField
Friend dd2 As DropDownList

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
sv = e.Row.FindControl("HiddenField1")
dd2 = e.Row.FindControl("dd2")
...

Protected Sub dd2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
    sv = sender.FindControl("HiddenField1")
    dd2 = sender.FindControl("dd2")
End Sub


Answers (2)