tags:

views:

52

answers:

1

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?

+1  A: 

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"] };
dcp
i am already haivng datatable which has the column name student_id which i want to make primary key in datable ow to do this, this is my exact question i dont want to add any other extra column to make primary key
NoviceToDotNet
@NoviceToDotNet - This code isn't adding any additional columns to the DataTable, it's setting the primary key using an existing column(s) already present in the DataTable. See my latest edit for how to do it with student_id.
dcp
@NoviceToDotNet: Don't let the `new` keyword throw you off. dcp's suggestion does not create any new `DataColumn` objects; rather, it creates a new *array* and puts the existing columns into this array to pass to the `PrimaryKey` property. This is the correct approach.
Dan Tao