📅  最后修改于: 2023-12-03 15:13:48.974000             🧑  作者: Mango
In C#, the GridView
control is commonly used to display tabular data on a webpage. The DataKeyNames
property of the GridView
allows you to specify which field(s) from the data source should be used as the primary key.
<asp:GridView id="GridView1" runat="server" DataKeyNames="FieldName"></asp:GridView>
GridView
- The ASP.NET control used to display tabular data.DataKeyNames
- The property used to specify the field(s) that will serve as the primary key.The DataKeyNames
property is important because it allows you to easily access the primary key value of a selected row in the GridView
. This is especially useful when you need to perform operations such as editing, deleting, or updating data.
Here's an example of how to use the DataKeyNames
property in C#:
<asp:GridView id="GridView1" runat="server" AutoGenerateColumns="False"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataKeyNames="EmployeeID">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
</Columns>
</asp:GridView>
In the example above, the DataKeyNames
property is set to "EmployeeID", which means that the EmployeeID
field from the data source will serve as the primary key.
To access the selected row's primary key value, you can use the SelectedDataKey
property in the event handler:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int employeeID = (int)GridView1.SelectedDataKey.Value;
// Perform operations using the selected employeeID
// ...
}
In this event handler, the SelectedDataKey
property is used to retrieve the value of the primary key (EmployeeID
) of the selected row in the GridView
. You can then perform any required operations using this value.
The DataKeyNames
property in C# is essential when working with the GridView
control, as it allows you to easily retrieve the primary key value of a selected row. This value can be used for performing various data operations.