Wednesday, 20 March 2013

Using DataKey property in DataGrid

The DataKey property is used to identify the primary key column in a DataGrid. The property will then be used to uniquely identify each row in the DataGrid. The value specified here must be a column in the database.

Here's some tips and tricks on how to use this property.

Using DataKey to identify visited links

View this post to know more about the feature.

Using DataKey to automatically update data

Setup a DataGrid and add all columns:



Scenario 1 : Update MaritalStatus in the DataGrid (without DataKey)

  • Specify an UPDATE statement in the DataGrid and assign all the parameters

Scenario 2: Update Marital status in the DataGrid (with DataKey)

  • Specify a DataKey value

  • Specify an UPDATE statement in the DataGrid and

  • Declare all the parameters
(Notice that I do not have to assign any value to the parameter which is present in DataKey)



In both scenarios, the data will be updated when the Save button is clicked.

In Scenario 2, since the row is identified using a DataKey (employeeid), the parameter in UPDATE statement will be automatically assigned to the DataKey provided that they both have the same name.

Tip 1 : Ensure that the case matches. DataKey value ‘Employeeid’ will not match Parameter ‘EmployeeID’

Tip 2 : Stadium does not allow spacing in Parameter name. Therefore, Scenario 2 will not work if there is spacing in DataKey/database column names.

Tip 3 : Only 1 value is allowed for DataKey

Tip 4 : If you need to use same DataKey across different DataGrids, you can use it as a CustomSetting

More information on DataKey at :

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys.aspx