Getting the row or sql value/index of the gridview row you just clicked

Getting the row you just clicked is not as obvious as it seems first hand

There are generally two cases that I need information from the row I clicked in a GridView (or listview, etc.).  The first being simply to get the index in the gridview, whether or not it was the first, fifth or 50th row.  That is pretty easy, but the second case, getting the index (or any) value of the SQL entry of the row just clicked is a little less obvious, though still pretty easy.  Here is a better explanation of that second one if it isn't clear: Say you have a GridView bound to a SqlDataSource (or Linq, etc.) and you have an column in that table that is Product_ID.  Your user is going to click on a button in one of those rows, say it is row 15, but the item Product_ID is 547.  You want to get 547 with no other information than the _Click event.


This is how you do it:



protected void btn_Click(object sender, EventArgs e)
   Button btnClicked = (Button)sender;
   // This will get you your GridViewRow
   GridViewRow row = (GridViewRow)btnClicked.NamingContainer;
   // This will get you the actual Index out of your SQL table
   string getIndex = this.GridView1.DataKeys[row.RowIndex].Value.ToString();
   // And this will just print it out to show it works
   Response.Write("Row Index: " + row.RowIndex.ToString() + "<br />");
   Response.Write("Sql Index: " + getIndex);


***IN ORDER FOR THIS TO WORK, you *have to* remember to add DataKeyNames="Product_ID" to the GridView tag, otherwise you will throw an OutOfBounds exception because your program won't know what the hell you are calling with DataKeys. 

Keep in mind this trick will work for any column in your table. I use this in my own app to populate a modal popup depending on what row was clicked, works very slick. 

Add comment