asma
asma

Reputation: 2825

Getting Gridview Row By Datakeynames

I have a gridview and it has datakeynames="Id"

I have that Id in code file. Now I want to get the row of a specific Id.

For example Id=1 then I want to get the row of gridview that has Id=1 I've used this code:

foreach (DataKey key in gdvMainList.DataKeys)
                {
                    if (Convert.ToInt32(key.Value) == consentReleaseId)
                    {
                        gdvMainListRow = gdvMainList.Rows[index];
                        break;
                    }
                    index++;
                }

Is there any better approach?

Upvotes: 1

Views: 14947

Answers (3)

franklins
franklins

Reputation: 3738

One thing you should be careful with your apporach is, if you have paging in your gridview, and if you are in a different page, you might end up pulling out wrong row or the row might not be found.

Instead of looping you can use a linq query on your datasource like

if your datasource is a list, obj = lObjs.Where( i => i.Id == consentReleaseId).First();

If you want to change something in the grid, you can change it in the obj and change the datasource.

Upvotes: 0

Blast_dan
Blast_dan

Reputation: 1125

Another option would be to bind the row ID into an element in the gridview row. Most often this occurs on an action link or button on the CommandArgument property.

<asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument='<%# Container.DataItemIndex %>' />

something like that. Then you can access the item and get the Row ID without any looping.

Upvotes: 1

James Johnson
James Johnson

Reputation: 46047

Another option would be loop through the items in the GridView until you find the matching key.

foreach (GridViewRow row in GridView1.Rows)
{
    if (GridView1.DataKeys[row.RowIndex]["ID"] == consentReleaseId)
    {
        gdvMainListRow = row;
        break;
    }
}

Upvotes: 4

Related Questions