EgyEast
EgyEast

Reputation: 1572

How to select a row in gridview by code based on its key value?

I'm using asp.net web forms application to view data of certain table in grid view & select a row in this grid view based on ID of this data row (Key Value) retrieved from query string I tried using this code in Code behind

gridview1.SelectedValue= Request.QueryString["RowToSelectID"];

but it said that selected value is a read only property and can't be assigned Is there another way to do that ?

Upvotes: 2

Views: 2138

Answers (1)

Mez
Mez

Reputation: 4726

Try the following and see here for more information.

var keyValue = 1; // Replace with your Convert.ToInt32(Request.QueryString["RowToSelectID"])
 for (int i = 0; i <= this.gridview1.DataKeys.Count - 1; i++)
 {
   if ((int)gridview1.DataKeys[i].Value == keyValue )
    {
       this.gridview1.SelectedIndex = i;
   }
}

I used the SelectedIndex. The record in the GridView having a key value of 1, will be selected.

Upvotes: 4

Related Questions