DataTable Editing and Finally Saving to Db

dg_pp

Member
Joined
Oct 24, 2012
Messages
6
Programming Experience
1-3
Hi,
How to edit a datatable(db col) on textbox lost focus event from textbox values. The edited values should display on listbox selectedindex changed event and finally on save button click event I want to save the updated records to db. Can I have some sample code for this?

I have some code in the textbox lost focus event but it is not saving the records to the datatable.
If dtTableUsers.Rows.Count > 0 Then
For i = 0 To dtTableUsers.Rows.Count - 1
dtTableUsers.Rows(i)("Mobile") = txtMobile.Text
Next
dtTableUsers.AcceptChanges()
End If

Thanks in Advance.
 
You don't need any code at all. Just use data-binding and it's all done for you. Here's an example of binding a DataTable to a ListBox and a TextBox:
'Bind the DataTable to a BindingSource.
myBindingSource.DataSource = myDataTable

With myListBox
    .DisplayMember = "Name" 'Display the contents of the Name column.
    .ValueMember = "ID" 'Expose the ID of the selected record via the SelectedValue property.
    .DataSource = myBindingSource
End With

'Bind the Description column to the Text property of the TextBox.
myTextBox.DataBindings.Add("Text", myBindingSource, "Description")
When the user selects an item in the ListBox, the corresponding data will be displayed in the TextBox. When the user selects a different record, the previous edit will be committed. In order to ensure that the last edit is committed to the DataTable, call the EndEdit method of the BindingSource before saving the data back to the database.

DO NOT call AcceptChanges on anything. If you do then you will not be able to save the changes back to the database. You only call AcceptChanges after saving the changes back to the database and it is called on a DataTable automatically by default when you pass it to the Update method of a data adapter. There are certain circumstances where you do need to call AcceptChanges explicitly but they are rare. They include when you are not passing the original DataTable to Update, e.g. you called GetChanges and passed the DataTable that it returned, and when you have set AcceptChangesDuringFill to False on your data adapter because you want to pass the same DataTable to multiple Update calls. Even in that second case, you'd probably still let the last data adapter do it for you.
 
Back
Top