简体   繁体   English

对数据表中的现有数据实施复合主键

[英]Enforcing composite primary key on existing data in datatable

I have a datatable with data. 我有一个datatable的数据。 I want to add composite primary key to this table (say on 2 columns) and check if any row in the datatable validates the composite primary key we set. 我想向该表添加composite primary key (例如2列),并检查数据表中是否有任何行可以验证我们设置的复合主键。 What I have done is I have added composite primary key to the datatable 我所做的是我向数据表添加了复合主键

DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["EmpId"];
keys[1] = dt.Columns["EmpName"];
dt.PrimaryKey = keys;

But I am not able to figure out how to check existing data and set RowError of respective rows. 但是我不知道如何检查现有数据并设置各个行的RowError。

Try with this: 试试这个:

1> For setting Row Errors 1>用于设置行错误

private void SetRowErrors(DataTable table)
{
    for(int i = 0; i < 10; i++)
    {
        table.Rows[i].RowError = "ERROR: " 
            + table.Rows[i][1];
    }
    DataSet dataSet = table.DataSet;
    TestForErrors(dataSet);
}

private void TestForErrors(DataSet dataSet)
{
    if(dataSet.HasErrors)
    {
        foreach(DataTable tempDataTable in dataSet.Tables)
        {
            if(tempDataTable.HasErrors) 
                PrintRowErrors(tempDataTable);
        }
        dataGrid1.Refresh();
    }
}

private void PrintRowErrors(DataTable table)
{
    foreach(DataRow row in table.Rows)
    {
        if(row.HasErrors) 
        {
            Console.WriteLine(row.RowError);
        }
    }
}

2>Check existing data for composite key violation: Refer the link shared below 2>检查现有数据是否违反组合键:请参阅下面共享的链接

Check existing data 检查现有数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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