Scenario:
- Excel file is read and displayed in datagrid.
- Values in sql server must be updated if excel values are different.
- Table in Sql server don’t have primary key
After all these steps, when I am about to update the table, it throws the error saying “Update requires a valid UpdateCommand when passed DataRow collection with modified rows.”
There is no primary key. So I need to use update command. BUt how and what would be in update command? importdata is dictionary where data from excel are stored. PLz help!!! What should I do now? I have No idea….
foreach (DataColumn column in ds.Tables[0].Columns)
{
string fieldName = column.ColumnName;
string fieldNameValueE = string.Empty;
if (importdata.ContainsKey(fieldName))
{
fieldNameValueE = importdata[fieldName];
foreach (DataRow dr in ds.Tables[0].Rows)
{
string fieldNameValueD = dr[fieldName].ToString();
if (fieldNameValueD != fieldNameValueE)
{
dr[fieldName] = fieldNameValueE;
}
}
}
}
da.Update(ds);
connection.Close();
So, let’s say we were dealing with a table that had a primary key:
If you were to use the
SqlCommandBuilder(which you cannot because you don’t have a primary key), it would build a statement a bit like this:So, you’re going to need to build an
UPDATEstatement that’s very similar to do it the way they do. But one thing you need to remember is it’s not just the statement, you also have to add all of the parameters to the command that you build – and that’s going to become pretty cumbersome.So, I have two recommendations for you:
ExecuteNonQueryin every iteration of the loop.The second recommendation would look like this: