I just spent a couple hours trying to convert a command.executenonquery to SqlDataAdapter.update(ds,"tablename").
It seems the only way for SqlDataAdapter.update to work is if I query the table, add parameters, add an insertcommand, and add a new row object, then call the update method. So:
Code:
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommnad("select * from table",conn);
da.Fill(ds,"table");
da.InsertCommand = new SqlCommand("insert into table (field1,field2) values (@field1,@field2)",conn);
da.InsertCommand.Parameters.Add("@field1",SqlDbType.Char,10);
da.InsertCommand.Parameters.Add("@field2",SqlDbType.Char,10);
da.InsertCommand.Parameters["@field1"].value = "field1";
da.InsertCommand.Parameters["@field2"].value = "field2";
DataRow row = ds.Tables["table"].NewRow();
row["field1"] = "field1";
row["field2"] = "field2";
ds.Tables["table"].Rows.Add(row);
da.Update(ds,"table");
Why do I need to set the values of the parameters AND make a new row object? It seems like I'm doing double work. I must be doing something wrong. In the end it works, but it bugs me that I need both to work.
Can someone chime off on this and confirm that this is indeed the way to do it or that I'm doing it wrong and how I should change my logic :)
Thanks