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?
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