RockOn
RockOn

Reputation: 197

How to get a GridView's selected Id?

I have a GridView that uses the select. I want to grab the RegistrantId of which row is selected. I've tried a bunch of ways and haven't had luck.

C#

  GridViewRow row = GridView1.SelectedRow;
        if ((row != null))
        {
            string registrantId = GridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            PnlEdit.Visible = true;
         }

I need to figure out what to put at string registrantId =. It needs to equal the value of the RegistrantId from that row.

This attempt above, for example, gives me a compile error for RowIndex stating that "EventArgs does not contain a definition for RowIndex."

Upvotes: 0

Views: 1129

Answers (1)

devlin carnate
devlin carnate

Reputation: 8591

You can find the RowIndex like so:

string registrantId = GridView1.DataKeys[e.RowIndex]

This assumes that you have the DataKeyNames property set in your gridview

<asp:GridView runat="server" ID="GridView1" DataKeyNames="RegistrantId" >

Also, if this method is triggered by an event handler, you might want to change your null check condition to:

protected void GridView1_RowSelecting(object sender, GridViewSelectEventArgs e)
{
   var registrantId = GridView1.DataKeys[e.RowIndex];
   if(registrantId != null)
   {
       PnlEdit.Visible = true;
   }

}

(You know the row exists because it was selected and that selection is what causes the event to trigger. The null check confirms you were able to obtain the registrantId from the row)

Upvotes: 1

Related Questions