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 开发者_如何学Ckey in gdvMainList.DataKeys)
{
if (Convert.ToInt32(key.Value) == consentReleaseId)
{
gdvMainListRow = gdvMainList.Rows[index];
break;
}
index++;
}
Is there any better approach?
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;
}
}
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.
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.
精彩评论