Sunday, December 27, 2009

How to get the current row in the grid view command event

This is what I faced a small problem when using GridView. I have a LinkButton element in the gridview and my goal is when user clicks on the button, I need to raise the grid view command event and in that event, I need to get the row values. But, the questions is how to get the current row in the grid view command event?  Below is the solution for it.

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

Note: Remember LinkButton class I used in the above code is assuming that the command event raised when clicked on the LinkButton control. If your requirement is not linkbutton then please place the corresponding control name.

Most of the times and most of the developers never use the property available to each and every object named NamingContainer. But, there are lot of advantages with this property. Especially when we write and render controls to page dynamically then this property will help a lot. And there are many properties which will help us to solve so many problems. Use the intellisense and try to know most of the properties available for a .NET control.

Hope, this will help you and you got what you need. Please let me know what you think on this post.

No comments:

Post a Comment