Update MS Access after editing bound listbox contents
I created a listbox bound to a datatable in C# connected to an MS Access database.
The idea was to display the contents of the table on the listbox and by selecting each one, it would then display the other values on textboxes all over the form. I was able to do just that. My next problem would be to update the database when editing the values in the textboxes. Now what I did was to create an update button which will then update the values in the listbox and then calling the Update() function for the dataAdapter the listbox is using but it doesn't seem to be affecting the table. My code is below.
private void btnUpdate_Click(object sender, EventArgs e)
{
if (lstEmployees.SelectedIndex > -1)
{
dEmployeesTable.Rows[lstEmployees.SelectedIndex].BeginEdit();
dEmployeesTable.Rows[lstEmployees.SelectedIndex]["LastName"] = txtLastName.Text;
开发者_运维问答 dEmployeesTable.Rows[lstEmployees.SelectedIndex].AcceptChanges();
dAdapter2.Update(dEmployeesTable);
}
}
Am I missing anything? I've tried this with datagridviews and it works fine including the editing and deleting. Not sure why it doesn't work on listboxes.
I've tried looking around and searching stackoverflow and other sites but i can't find anything close.
When using Update, the order of execution is as follows:
The values in the DataRow are moved to the parameter values.
The OnRowUpdating event is raised.
The command executes.
If the command is set to FirstReturnedRecord, then the first returned result is placed in the DataRow.
If there are output parameters, they are placed in the DataRow.
The OnRowUpdated event is raised.
AcceptChanges is called.
so remove the line of dEmployeesTable.Rows[lstEmployees.SelectedIndex].AcceptChanges();
and try again
AcceptChanges
commits changes to the dataset or datatable. All added and modified rows
become "Unchanged"
.
when you call Update (..)
, the data adapter doesn't
find any modified rows to update. Update ()
calls AcceptChanges ()
internally.
精彩评论