How to use SqlDataAdapter to update multiple row in c#

1.2k views Asked by At

I use SqlDataAdapter and SqlCommandBuilder to perform DML transactions on rows in a SQL Server database.

I am able to add and delete multiple rows in database but update.

This is the code:

SqlDataAdapter da = new SqlDataAdapter(@"select top 1 * from " + tableName, 
ConnectionString);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);

I'm trying to use AcceptChanges, so far it doesn't work.

2

There are 2 answers

0
Bader On BEST ANSWER

i have found reason, a column is set DateTime type. So, this Column isn't saving to the database.

1
aspiring On

This is how I usually do within C#. If you want to give this a try.

//you may put this as a direct string or in a static class when layering
//you can pass table as hard-coded value or as a parameter
String SqlQuery = "UPDATE " +
            " [tableName] " +
            " SET [Column1ToBeUpdated]=@Column1Value," +
            " [Column2ToBeUpdated]=@Column2Value" +
            " WHERE ([ColumnxWithCondition] = @Condition)";

//add OR, AND operators as per your needs
//choose the correct SqlDbType for your column data types

public bool UpdateMyTable(String SqlQuery, Someclass obj)
 {
        SqlCommand sCommand = new SqlCommand(this.SqlQuery, (new SqlConnection(ConnectionString)));

        sCommand.Parameters.Add("@Column1Value", SqlDbType.VarChar).Value = obj.col1Value;
        sCommand.Parameters.Add("@Column2Value", SqlDbType.VarChar).Value = obj.col2Value;
        sCommand.Parameters.Add("@Condition", SqlDbType.VarChar).Value = obj.condition;

        sCommand.Connection.Open();
        var rowsAffected = sCommand.ExecuteNonQuery();
        sCommand.Connection.Close();
        return rowsAffected > 0;
 }

 //if you want to see the number, you may return rowsAffected