I have a datatable from database on the basis of some query.
I want that datatable to have a primary key for an existing column.
How can I do this?
The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns: // set the primary key based on two columns in the DataTable DataTable dt = new DataTable("MyTable"); dt.
PrimaryKey = new DataColumn[] { table. Columns["Id"] };
Each table can only have one primary key. Access can automatically create a primary key field for you when you create a table, or you can specify the fields that you want to use as the primary key.
A primary key defines the set of columns that uniquely identifies rows in a table. When you create a primary key constraint, none of the columns included in the primary key can have NULL constraints; that is, they must not permit NULL values.
Assuming the name of the column in your data table you want to be the primary key is called pk_column
, you could do this (assume dt
is your DataTable
):
dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column"] };
If your primary key is made up of multiple columns, you can add them to the array, like so:
dt.PrimaryKey = new DataColumn[] { dt.Columns["pk_column1"], dt.Columns["pk_column2"] };
So if you were making student_id your primary key, you could do this:
dt.PrimaryKey = new DataColumn[] { dt.Columns["student_id"] };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With