.net – Even if GridView.DataKeyNames is set, Gridview.DataKeys[] is still empty

asp.netnet

GridView.DataKeynames stores the names of the primary key fields for the items displayed in a GridView control.

1) Even though I’ve set DataKeyNames, GridView still doesn’t store record’s primary key value(s) in DataKey object:


protected void SqlDataSource1_Selected(object sender, 
          SqlDataSourceStatusEventArgs e)
{
      Label2.Text = GridView2.DataKeys[0].Value.ToString();//exception
}

Why not?

2) I assume when DataKeyNames is set, DataKey object stores both original and new values of a primary key ( assuming we issued an update command ) and when the update is finished, DataKey object discards the original value(s)?

Thank you

Best Answer

I guess this is too late... But first, you are trying to get data keys right after data retrieval and not after data bind. DataKeys do not get populated until DataBind.

Second, data keys do not store new post-update values. They are copies of what was available during binding, stored in the view state, and used primarily to locate records after a post back w/o doing another bind.

Related Topic