📜  c# get gridview DataKeyNames - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.974000             🧑  作者: Mango

C# Get GridView DataKeyNames

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.

Syntax
<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.
Purpose

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.

Example

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.

Conclusion

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.