简体   繁体   中英

What is the purpose of Unique property in datatable in C#?

Why do we use unique key in data table in C#?

i need answer with syntax.. how to set unique key

objDataColumn.Unique = objDataTable.Columns.Add("Student ID");
objDataTable.Columns.Add("Student Id", typeof(int));

thanks in Advance

Unique constraint will ensure your column will never have duplicate value. see msdn

DataColumn column = new DataColumn("Student ID");
column.DataType = System.Type.GetType("System.Int32");
column.Unique = true;
objDataTable.Columns.Add(column);

Simple:

DataColumn dt = new DataColumn("Student ID", typeof(int));
dt.Unique = true;
objDataTable.Columns.Add(dt);

Or if you're a fan of one-liners:

objDataTable.Columns.Add(new DataColumn("Student ID", typeof(int)) { Unique = true });

for primary key:

DataColumn[] keys = new DataColumn[1];
keys[0] = objDataTable.Columns[0];
objDataTable.PrimaryKey = keys;

for constraint:

var c= new UniqueConstraint(new DataColumn[] { objDataTable.Columns[0]});
objDataTable.Constraints.Add(c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM