How to get selected GridView row in GridViewCommandEventArgs?

Posted by Raja under ASP.NET on 9/30/2009 | Views : 29269 | Status : [Member] | Replies : 2
I have a link button in which I am specifying commandName as "UpdateMe", and writing GridViewCommandEventArgs event in the code behind.

How to get the selected row for that LinkButton?

(In my scenario, I do not want to write GridViewRowUpdating event)

Thanks

Regards,
Raja, USA



Responses

Posted by: Poster on: 9/30/2009 [Member] Starter

Up
0
Down
Use following code snippet.


GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

You will have the selected row in "row" variable. Start using row.FindControl to find all the controls available in that row.

Hope this helps.

Thanks

Raja, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Rtpharry on: 9/30/2009 [Member] [MVP] Bronze

Up
0
Down
The way that I do it is to take it from the e.CommandArgument like this:

int index = Convert.ToInt32(e.CommandArgument);


If you are using a BoundField or one of the built in row types it will already be populated.

If not you can populate it with either your PK field or the RowIndex field like this:

CommandArgument='<%# Eval("id") %>'


OR

CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'



I like the elegance of Poster's reply but something to bear in mind, I am not sure if this would work if you had a naming container control inside your templatefield as it would get the wrong container (first one it found) - mind you - this is not a common scenario.

Raja, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response