How do I use GridView.DataKey/DataKeyNames in codebehind?

Posted by Jajati under ASP.NET category on | Points: 40 | Views : 7132
myGrid = new GridView();
myGrid.AutoGenerateColumns = false;
myGrid.AutoGenerateSelectButton = true;
myGrid.SelectedIndexChanged += new EventHandler(myGrid_SelectedIndexChanged);
myGrid.DataSource = myDataSet;
if (this.Page.IsPostBack == false)
grdArticlesByCategory.DataKeyNames = {"ID_1", "ID_2", "ID_3"};

void grdArticlesByCategory_SelectedIndexChanged(object sender, EventArgs e)
DataKey dKey = myGrid.DataKeys[myGrid.SelectedIndex];
1stID = dKey.Values["ID_1"].ToString();
2ndID = dKey.Values["ID_2"].ToString();
3rdID = dKey.Values["ID_3"].ToString();
1.The DataKeyNames property is used to identify a record uniquely in the GridView control. A column in the data source is assigned to the DataKeyNames property to identify the record.
2.You must set the DataKeyNames property for the automatic updating and deleting features of the GridView control to work. The values of these key fields are passed to the data source control in order to match the row to update or delete.
3.To set this property declaratively, use a comma-separated list of field names.

public virtual string[] DataKeyNames { get; set; }

Please refer this link too

Comments or Responses

Login to post response