Search code examples
c#asp.netfindcontrol

Accessing data in RowCommand


Im new to C# and in VB i could do the following:

Protected Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
        If e.CommandName = "CommandName" Then

            Dim label1 As Label = e.Item.FindControl("label1")

            Response.Write(label1.Text))


        End If

    End Sub

in C# and the RowCommand, I cannot use findcontrol to access a controls value. I want to get the value of two label's so I can use them when I call a method in the rowcommand

Update: In C# when I do

Label label1 = (Label)e.Item.FindControl("label1"); 

or

Label label1 = (Label)e.Row.FindControl("label1"); 

I do not have Row or Item available


Solution

  • I added a CommandArgument in the button and was able to get what I needed:

    .aspx in the gridview

      <asp:Button ID="btnActive" CommandArgument='<%# Eval("Id")%>' CommandName='<%# Eval("Activity")%>' Text='<%# Eval("Activity")%>' runat="server" />
    

    then in the RowCammand in the .aspx.cs

      protected void gridview_RowCommand(object source, System.Web.UI.WebControls.GridViewCommandEventArgs e)
                    {
                        if (e.CommandName == "Disable")
                        {
                              string[] args = e.CommandArgument.ToString().Split(',');
                              Guid gArticleId = new Guid(args[0]);
    
                              Response.Write(gArticleId);
    
                        }