Dynamically set DataKeyNames in gridview

How can I set the value of a DataKeyNames gridview in C # code?

since my gridview is dynamically generated, I need to install it from a .cs file

+5
source share
4 answers

Enter the code in the cs file, for example

Gridview d

protected void Page_Load(object sender, EventArgs e)

{
    d = new GridView();

    d.DataKeyNames = new string[] { "Column1", "Column2" };
    form1.Controls.Add(d);
}
+12
source

You can set it like any other grid property:

myGrid.DataKeyNames = new string[] {"Id", "Name"};

This corresponds to the following declarative code:

<asp:GridView id="myGrid" DataKeyNames="Id,Name" ... />
+5
source

- :

myGridView.DataKeyNames =new string[]{"PrimaryKeyId"} 
+2

DataKeyNames GridView.

{YourGriViewID}.DataKeyNames = new string[] {"ColV", "Col"};
+1

All Articles