Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

marking existing column as primary key in datatable

Tags:

.net

datatable

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?

like image 409
NoviceToDotNet Avatar asked Sep 01 '10 20:09

NoviceToDotNet


People also ask

How to set DataTable primary key?

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.

How to set primary key in DataTable VB net?

PrimaryKey = new DataColumn[] { table. Columns["Id"] };

Can a table have two primary keys?

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.

Can primary key be NULL?

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.


1 Answers

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"] }; 
like image 184
dcp Avatar answered Oct 05 '22 01:10

dcp