简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM