How can I get the value of a hidden field in a grid view?

the order number of the hidden grid field is 7.

when i click the button on the line

string sValue = ((HiddenField)GridView1.SelectedRow.Cells[7].FindControl("HiddenField1")).Value; 


gives an error which is "Object reference not set in object instance".


                <asp:HiddenField ID="HiddenField1" runat="server" 



C # side

else if (e.CommandName == "View")
    string sValue = ((HiddenField)GridView1.SelectedRow.Cells[7].FindControl("HiddenField1")).Value;                   



source to share

3 answers

Have you tried this?

HiddenField field = (HiddenField)GridView.Rows[GridView.SelectedIndex].FindControl("HiddenField1");


If so, how about this?

HiddenField field = GridView1.Rows[e.RowIndex].FindControl("HiddenField1") as HiddenField;


Here's another example you could try,

if(e.Row.RowType == DataControlRowType.DataRow)
     HiddenField field = e.Row.FindControl("HiddenField1") as HiddenField;


Hope this helps ... cheers



Discard part of the cells

If you have a selected line:

string sValue = ((HiddenField)GridView1.SelectedRow.FindControl("HiddenField1")).Value;


If you have e.rowIndex from the command argument:

string sValue = ((HiddenField)GridView1.Rows[e.rowIndex].FindControl("HiddenField1")).Value;




You are trying to access the SelectedRow even though I cannot see the code when you actually select the row. I am assuming you are only using some custom command button, which does not actually set the selected line. Fix this and it should work.

If you can't / don't want to, you need to write yourself some method to find the row you want, and then use the FindControl method to access the hidden field, getting the value ...

Or try posting the more complete source code ...



All Articles