【问题标题】:Programmatically Add a Datakey to an Existing Set of DataKeys以编程方式将数据键添加到现有的数据键集
【发布时间】:2012-08-11 04:59:48
【问题描述】:

我有一个 GridView,它有几个数据键。在特定情况下,我需要在页面的 Load 事件期间从后面的代码中添加一个额外的数据键。

如何以编程方式将数据键添加到 GridView 中的现有数据键集?

【问题讨论】:

    标签: asp.net gridview datakey


    【解决方案1】:

    最简单的方法是将 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
    

    【讨论】:

      【解决方案2】:

      试试这个

       //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;
      

      【讨论】:

        猜你喜欢
        • 2013-07-10
        • 2012-12-13
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        • 2011-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多