Haruna Ado
Haruna Ado

Reputation: 47

Get a hidden field in Gridview on RowCommand Event

If I have two buttons on gridview and each performing different function. For example my code below,

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
        //Do something else
    }
    else if (e.CommandName == "View Cert")
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GridView1.Rows[index];
        errorlab.Text = row.Cells[3].Text;
    }

}

The value of cell 3 is a hidden field and there is a value in the database that's binding to hidden field but with my code I couldn't get the value. The errorlab label is showing nothing. Maybe I'm missing something.

Upvotes: 0

Views: 7573

Answers (3)

ani07
ani07

Reputation: 158

I would like to suggest an answer, the command argument will not fetch you the row index. Instead it will give you what you bind during gridview data binding.

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      if (e.CommandName == "Select")
      {
        //Do something else
      }
      else if (e.CommandName == "View Cert")
      {
        //The hidden field id is hdnProgramId
        HiddenField hdnProgramId = (((e.CommandSource as LinkButton).Parent.FindControl("hdnProgramId")) as HiddenField);
      }

   }

This will try to locate the hidden field from the gridview row context.

Upvotes: 2

Dennis R
Dennis R

Reputation: 3237

Always try to avoid referring cells by it's index position in gridview as it may result in changing the code if you happen to add/delete few more columns in the grid in the future which might result in undesired result. Also note that hiddenfield does not have a Text property but rather a Value property to access it's value.

If you know the hiddenfield's name then better try accessing it by it's name. Let's say you have your hiddenfield defined as below in your gridview

 <ItemTemplate>
     <asp:HiddenField ID ="hdnField" runat="server" Value='<%# Bind("ErrorLab") %>'/>
 </ItemTemplate>

Then in your GridView1_RowCommand you can do

int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

HiddenField hdnField = (HiddenField)row.FindControl("hdnField");
errorlab.Text = hdnField.Value;

Upvotes: 0

Kiran Hegde
Kiran Hegde

Reputation: 3681

If you have futher controls on the gridview cell then you have to access them using the Controls property

 HiddenField hiddenField =row.Cells[3].Controls[0] as HiddenField;
 if(hiddenField != null)
    errorlab.Text = hiddenField.Value;

You have to use the correct index for the controls. Debug the code and check what is position of the control in row.Cells[3].Controls.

Upvotes: 0

Related Questions