我有一個具有幾個數據鍵的GridView。在特定情況下,我需要在頁面的Load事件期間從代碼中添加一個額外的數據鍵。以編程方式將數據鍵添加到現有的DataKeys集合
如何以編程方式將數據鍵添加到GridView中現有的一組數據鍵?
我有一個具有幾個數據鍵的GridView。在特定情況下,我需要在頁面的Load事件期間從代碼中添加一個額外的數據鍵。以編程方式將數據鍵添加到現有的DataKeys集合
如何以編程方式將數據鍵添加到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;