いくつかのデータキーを持つGridViewがあります。特定の状況下では、ページのLoadイベント中に、コードビハインドからデータキーを追加する必要があります。
GridViewの既存のデータキーのセットにプログラムでデータキーを追加するにはどうすればよいですか?
これを行う最も簡単な方法は、DataKeyNamesのString配列をArrayListに変換し、新しいDataKeyNameを追加してから、このArrayListをString()配列に変換し直してから、これを使用してGridviewのDataKeyNamesプロパティを設定することです。次に例を示します。
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
これを試して
//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;