0

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?

Carth
  • 2,303
  • 1
  • 17
  • 26
Matt Hanson
  • 3,458
  • 7
  • 40
  • 61

2 Answers2

3

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
Martin-Brennan
  • 917
  • 7
  • 19
3

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;
codingbiz
  • 26,179
  • 8
  • 59
  • 96