Create a PrimaryKey for a DataTable
CreateAPrimaryKeyForADataTable.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html>
<script runat="server">
void Button1_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.TableName = "Books";
DataColumn dc1 = new DataColumn();
dc1.ColumnName = "BookID";
dc1.DataType = typeof(int);
dt.Columns.Add(dc1);
//this line set the 'BookID' column to DataTable PrimaryKey
dt.PrimaryKey = new DataColumn[] {dc1};
DataColumn dc2 = new DataColumn();
dc2.ColumnName = "BookName";
dc2.DataType = typeof(string);
DataColumn dc3 = new DataColumn();
dc3.ColumnName = "Author";
dc3.DataType = typeof(string);
dt.Columns.AddRange(new DataColumn[] { dc2,dc3 });
dt.Rows.Add(new object[] { 1, "Creating a Website: The Missing Manual, Third Edition", "Matthew MacDonald" });
dt.Rows.Add(new object[] { 2, "HTML5 Step by Step", "Faithe Wempen" });
dt.Rows.Add(new object[] { 3, "Microsoft® Expression® Web 4 Step by Step", "Chris Leeds" });
/*
Uncomment this line to get an error because 'BookID'
column is PrimaryKey. So it must be unique.
*/
//dt.Rows.Add(new object[] { 3, "test book", "test author" });
GridView1.DataSource = dt;
GridView1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to create a PrimaryKey for a DataTable in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
How to create a PrimaryKey for a DataTable in ado.net
</h2>
<hr width="550" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="550"
>
<HeaderStyle BackColor="SaddleBrown" Height="35" />
<RowStyle BackColor="BurlyWood" />
<AlternatingRowStyle BackColor="Wheat" />
</asp:GridView>
<br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Populate GridView"
Height="45"
Font-Bold="true"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>

- How to count columns in a DataTable
- How to delete a row from a DataTable
- How to create multi-column primary key for a DataTable
- How to use DataTable AcceptChanges() method
- How to use DataTable RowDeleting event
- How to copy one DataTable to another DataTable
- How to create a DataView
- How to create a DataTable with distinct rows from a DataView
- How to add a new row to the DataView
- How to create a DataTable from a DataView