Compare two datarows

I have a datatable with several rows inside it. I have one more row and I want to check if this row is a duplicate of existing rows in datatable. So I tried:

DataTable dataTable = GetTable(); if (dataTable.Rows.Count > 1) { for (int i = 0; i < dataTable.Rows.Count; i++) { var dataRow = dataTable.Rows[i]; if (dt.Rows.Contains(dataRow) && dt.Rows.Count != 0) // Giving error continue; dt.ImportRow(dataRow); return dataRow; } } 

Here my dataTable may also be empty / empty for the first time.

But its error output:

There is no primary key in the table.

Can anybody help me. If additional code is required, just comment.

+4
source share
2 answers

Can't you add PK to your DataTable?

I think the code would be something like this:

 dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["Id"] }; 
+1
source
 DataTable dataTable = GetTable(); if (dataTable.Rows.Count > 1) { for (int i = 0; i < dataTable.Rows.Count; i++) { var dataRow = dataTable.Rows[i]; if (dt.Rows.Contains(dataRow) && dt.Rows.Count != 0) // Giving error continue; dt.ImportRow(dataRow); return dataRow; } } 

I assume that your dt variable should be your dataTable variable, if you get an error message indicating that your table does not have a primary key, it could be because you are using the wrong variable and that there really is no primary key or table associated with the variable you are trying to use.

so I assume the code should look like this:

 DataTable dataTable = GetTable(); if (dataTable.Rows.Count > 1) { for (int i = 0; i < dataTable.Rows.Count; i++) { var dataRow = dataTable.Rows[i]; if (dataTable.Rows.Contains(dataRow) && dataTable.Rows.Count != 0) // Giving error continue; dataTable.ImportRow(dataRow); return dataRow; } } 
0
source

Source: https://habr.com/ru/post/1392772/


All Articles