Creating primary keys in DataTable RRS feed

  • Question

  • How to Create primary keys in datatable

    i need a simple way, cause  i realy don't about primary in datatable


    Saturday, July 14, 2007 4:12 AM

All replies

  • Primary column in DataTable is just a regular column, where Unique property of it set to True. You could create such a column using next kind of code


    Dim column As DataColumn = New DataColumn("MyUniqueColumnName")
        column.DataType = System.Type.GetType("System.Int")
        column.Unique = True


    Saturday, July 14, 2007 11:45 AM
  • ALTER TABLE 'your table' ADD CONSTRAINT 'name you primary key' PRIMARY KEY ('one or more fields of your table');

    this query your modify and execute in your database.

    or using this code.


    string myQuery="Alter table products add constraint 'pk_id' primary key (product_id)";

    SqlCommand dbCmd = dbConnection.CreateCommand();
    dbCmd.CommandText = myQuery;

    int rowsAffected = dbCmd.ExecuteNonQuery();

    dbCmd.Dispose(); dbCmd = null;
    Saturday, July 14, 2007 3:53 PM