How to check if datatable.PrimaryKey is set
i have a datatable which i have to assign a primary key if it doesn't already have one. i tried :
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
But the PrimaryKey (in this case) not null. When i checked it contained : {System.D开发者_StackOverflow社区ata.DataColumn[0]} How can i check on that?
Javier's answer is correct, but lacks explanation. So here it is, DataTable.PrimaryKey property is collection of DataColumns. If the DataTable PrimaryKey property is not set than length of the collection will be 0. If DataTable has one or more fields defined as primary key than length of the PrimaryKey property will reflect this. So, checking like this:
if (ds.Tables[0].PrimaryKey.Length == 0)
will tell us if no columns are added to represent the primary key, and the part
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
would actually add DataColumn(s) to collection of columns held by PrimaryKey property.
Looks like it is not that hard after all i already tried this but apparently did something wrong because when i just tried again it did work :
DataColumn[] esl = new DataColumn[] { dt.Columns["Naam"] };
if (ds.Tables[0].PrimaryKey == null || ds.Tables[0].PrimaryKey == esl)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
if (ds.Tables[0].PrimaryKey.Length == 0)
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
精彩评论