开发者

How to check if datatable.PrimaryKey is set

开发者 https://www.devze.com 2023-03-03 03:01 出处:网络
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)

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"] };
0

精彩评论

暂无评论...
验证码 换一张
取 消