Hi,
I have rowcommand function, in which i m obtaining sr_no as datakey from a link button. now i want to know which row was that. How to get row index this way ?

Dani AI

Generated

Good thread — 's two quick approaches (using the command argument as an index or pulling the row from the control's container) are fine when you can change the markup or the command argument. If you only have the datakey value (your sr_no) inside RowCommand and need the GridView row index, search the GridView.DataKeys collection for that value. That gives you the zero‑based row index for the current page without depending on how the command was wired up.

// srNo is the datakey value you received in the RowCommand (as string)
int rowIndex = -1;
for (int i = 0; i < GridView1.DataKeys.Count; i++)
{
    var keyVal = GridView1.DataKeys[i].Values["sr_no"];
    if (keyVal != null && keyVal.ToString() == srNo)
    {
        rowIndex = i;
        break;
    }
}

Notes and common pitfalls: make sure the GridView has DataKeyNames="sr_no" so DataKeys are populated; the rowIndex above is page‑relative (as hinted, it’s zero‑based). If you need an absolute index in the full data source, use:

int absoluteIndex = (GridView1.PageIndex * GridView1.PageSize) + rowIndex;

For repeated lookups or large grids, build a lookup map in the GridView.DataBound handler to avoid scanning every time:

var map = new Dictionary<string,int>();
for (int i = 0; i < GridView1.DataKeys.Count; i++)
{
    var k = GridView1.DataKeys[i].Values["sr_no"]?.ToString();
    if (!string.IsNullOrEmpty(k)) map[k] = i;
}

Use the map for O(1) lookups. If you use multiple DataKeyNames, pull the correct key name from DataKeys[i].Values["keyName"].

Recommended Answers

All 4 Replies

So im guessing that you have a LinkButton or something like that to trigger the rowcommand event.

I think i have used this before and it works.

int rowIndex = Convert.toInt32(e.CommandArgument);

if that one above dont work you can try this lets say again that the rowcommand is trigger by a linkbutton you will do this.

GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int rowIndex = row.RowIndex;

hey thanks !! :)

Always!!! :)

I think Jibsosn is answered!!!! he is right try later one code --it may be return index from 0 to onwords
then you can find out the rows
Thnx Shakeb Ahmad Khan

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.