There\'s a few tutorials out there on this, but I\'m assuming I must have implemented something wrong, because the code I followed from combined tutorials is not working as it s
It looks to me like you're never setting a SQL update statement, only select statements.
You'll need to add something in like:
sda.UpdateCommand = "UPDATE TABLE SET ..."
Or create a new dataAdapter/command to handle your update
Once you have that in place, calling update on sda should work.
Revised:
If it were me, I would use SqlCommand for your update statement.
private void UpButton_Click(object sender, EventArgs e)
{
try
{
using(con = new SqlConnection(Properties.Settings.Default.SchoolConnectionString))
{
con.Open();
string sqlCommand = "Update (Table) set value=@Value where id=@ID";
SqlCommand cmd = new SqlCommand(sqlCommand, con);
cmd.Parameters.AddWithValue("@Value", updatedValue);
cmd.Parameters.AddWithValue("@ID", idOfRowToUpdate);
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected == 1)
{
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Things to note:
You'll need to get the values you're updating from your table and replace it for UpdatedValue and idOfRowToUpdate.
You'll need to form the UPDATE command for your table.
the "Using" brackets help properly dispose of your connection object.
Technically with the using brackets con.Close() isn't required. I do it just in case.
Revision #2:
Ok, I did some more research into SqlDataAdapter and how it functions in regards to a datatable, it looks like this is much easier than I thought.
You should be able to drop in this new code to the UpButton_Click method and have it work:
try
{
DataTable newDT = dt.GetChanges();
if(newDT != null)
{
sda.Update(newDT);
}
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
According to This StackOverflow Article, this should be all you need to make the update.