Programmatically Add a Datakey to an Existing Set of DataKeys

4.1k Views Asked by At

I have a GridView that has a few datakeys. Under a specific set of circumstances, I need to add an additional datakey from the code behind during the page's Load event.

How does one programmatically add a datakey to an existing set of datakeys in a GridView?

2

There are 2 best solutions below

0
On BEST ANSWER

The easiest way to do this is to convert the String array of DataKeyNames to an ArrayList, add the new DataKeyName, then convert this ArrayList back to a String() array, and then set the Gridview's DataKeyNames property using this. Here is an example:

Dim arr As New ArrayList()
Dim keys As String() = GridView1.DataKeyNames

//Convert to an ArrayList and add the new key.
arr.AddRange(keys)
arr.Add("New Key")

//Convert back to a string array and set the property.
Dim newkeys As String() = CType(arr.ToArray(Type.GetType("System.String")), String())
GridView1.DataKeyNames = newkeys
0
On

Try this

 //get length of existing keys
 int keyLength = MyGrid.DataKeyNames.Length;

 //create newkeys array with an extra space to take the new key
 string[] newkeys = new string[keyLength+1];

 //copy the old keys to the newkeys array
 for (int i = 0; i < keyLength; i++)
    newkeys[i] = MyGrid.DataKeyNames[i];

 //add the new key in the last location
 newkeys[keyLength] = "MyNewKey";

 //update your datakeys
 MyGrid.DataKeyNames = newkeys;