Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > Databinding adding and saving new records
 

Databinding adding and saving new records

Hello,

VS 2008.

I am using a typed dataset and reading and writing to a xml file. The table is very small, so don't need any database.

This is not a master/child detail. The grid displays all the people, and the text boxes will display what is selected in the grid so that they can be edited and added.

I am having a small issue with adding a new person. I have found a work around, which means suspending binding on the bindingsource before clearing the contents of the text boxes. By clicking the clear button. The user will add a new person and then click add. I am thinking is there a way to do this without having the user click the clear button, to suspend binding.

I have also tried: which clears all the text boxes automatically.

Code Snippet
DataRowView drv = (DataRowView)this.bsAddressBook.AddNew();

All the data binding has been set in the designer for the text boxes, datagrid and binding source.

This is not a big issue. I think I am just looking for a way just to have a 'Add New' and 'Save' button. The save will save any new person added, and save any updates. The add new will clear the text boxes so that the user can enter the details.

Many thanks,

Code below:

Code Snippet

private void AddressBook_Load(object sender, EventArgs e)
{
//Read in and fill the datagrid.
this.ReadAddressBookXML();
}

//Add a new address book details to the xml file
private void btnAddNew_Click(object sender, EventArgs e)
{
//Create a new data row
dsCATDialer.AddressBookRow nr = dsCATDialer.AddressBook.NewAddressBookRow();

nr.Name = this.txtName.Text;
nr.Email = this.txtEmail.Text;
nr.PhoneNumber = this.txtPhoneNumber.Text;
nr.Notes = this.txtNotes.Text;

//Add data row to the addressbook table
dsCATDialer.AddressBook.Rows.Add(nr);

//Resume binding so that the text boxes will contain the bounded details.
if (this.bsAddressBook.IsBindingSuspended)
{
this.bsAddressBook.ResumeBinding();
}

//Move to the last record which is the most recent one added.
this.bsAddressBook.MoveLast();

//Save the changes to the xml file.
this.WriteAddressBookXML();
}

//Save the currently selected row
private void btnSave_Click(object sender, EventArgs e)
{
//Get the current row that is selected.
DataRowView drv = (DataRowView)this.bsAddressBook.Current;

//Enter the updated details.
drv["Name"] = this.txtName.Text;
drv["PhoneNumber"] = this.txtPhoneNumber.Text;
drv["Email"] = this.txtEmail.Text;
drv["Notes"] = this.txtNotes.Text;

//Commit the changes to the dataset.
this.bsAddressBook.EndEdit();

//Resume binding so that the text boxes will display the bounded records.
if (this.bsAddressBook.IsBindingSuspended)
{
this.bsAddressBook.ResumeBinding();
}

//Save the changes to the xml file.
this.WriteAddressBookXML();
}

//Clear the contents before adding a new row
private void btnClear_Click(object sender, EventArgs e)
{
//Suspend the binding so that text boxes can have there contents cleared.
this.bsAddressBook.SuspendBinding();

//Clear all the contents for filling in the new details.
this.txtName.Clear();
this.txtPhoneNumber.Clear();
this.txtEmail.Clear();
this.txtNotes.Clear();
}

//Delete the currently selected record
private void btnDelete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete " + this.txtName.Text + "?", "Delete Item",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
this.bsAddressBook.RemoveCurrent();
}
}

steve1_rm  Thursday, July 10, 2008 3:18 AM

Hi steve1_rm,

I have to say that you have done a good job.

Based on my understanding, you want to add new person without using clear button when using DataBinding.

In the clear button click’s event handler, we know that the code is used to suspend the Data Binding and clear the text of the textbox. What we want is to place this code into another place.

In my opinion, we can achieve the goal by dealing with addNew button click’s event handler where we need to following steps:

1. Save the previous record.

2. Suspend the Data Binding of the BindingSource.

3. Clear the text of all the TextBox.

4. Call the AddNew method of BindingSource which will fire the AddingNew event of the BingdingSource.

Still, we need deal with the handler of AddingNew event in which we should resume the Data Binding. Note that before we clear the TextBox we should suspend Data Binding first.

Please feel free to contact me if you have further questions.

Best Regards,

Bruce Zhou

Bruce.Zhou  Wednesday, July 16, 2008 9:02 AM

Post Updated: handle Escape key at Dialog level, not just for txtName control.

I would simplify the application, by dropping the Clear and Save buttons,and allow the Framework to setup the text boxes.

These are the changes I would recommend:

private void AddressBook_Load(object sender, EventArgs e)
{

// Read in and fill the datagrid.
this.ReadAddressBookXML();

// If no entries in address book, set for new address

if (bsAddressBook.Count == 0)

{

SetForNewAddress();

}

}

private void btnAddNew_Click(object sender, EventArgs e)
{

SetForNewAddress();

}

// Drop btnSave_Click & btnClear_Click event handlers

void txtName_Validating(object sender, CancelEventArgs e)

{

txtName.Text = txtName.Text.Trim();

string errorMessage = "";

if (txtName.Text.Length == 0)

{

errorMessage = "Please enter a name";

}

/*

else

{

// Optional - do additional validation, such as checking for duplicate name

}

*/

if (errorMessage.Length != 0)

{

errorProvider.SetError(txtName, errorMessage);

e.Cancel = true;

}

}

void txtName_Validated(object sender, EventArgs e)

{

//End editing ofnew record

bsAddressBook.EndEdit();

// Re-allow adding / deleting of records

btnAddNew.Enabled = btnDelete.Enabled = true;

}

void bsAddressBook_CurrentChanged(object sender, EventArgs e)

{

btnAddNew.Enabled = btnDelete.Enabled = true;

}

private void AddressBook_FormClosing(object sender, FormClosingEventArgs e)

{

// Ensure changes to current record are kept

bsAddressBook.EndEdit();

//Save address book

WriteAddressBookXML();

}

protected override bool ProcessDialogKey(Keys keyData)

{

// Allow user to cancel edit of new / current record

if (keyData == Keys.Escape)

{

this.ActiveControl.CausesValidation = false;

bsAddressBook.CancelEdit();

this.ActiveControl.CausesValidation = true;

}

return base.ProcessDialogKey(keyData);

}

// Helper functions

private void SetForNewAddress()

{

bsAddressBook.AddNew();

btnAddNew.Enabled = btnDelete.Enabled = false;

txtName.Focus();

}

NOTE: I used an ErrorProvider to display validation erors. This shows a circular red icon next to the text box with the error, with a ToolTip showing the error message (hover over icon with mouse cursor). To add the ErrorProvider, drag the component from the Toolbox to your form.

You'll also need to setup the missing event handlers in the Designer (txtName - Validating & Validated, bsAddressBook -CurrentChanged and AddressBook -FormClosing).


So, on clicking the Add button, the Framework will automatically clear the textboxes (as you found). I've also disabled the Add & Delete buttons to indicate useris setting up a new entry.

When the user has at least entered a name, which is the minimum I've assumed is required for a record, I end editing of the record and re-enable the buttons.

If the user clicks on another record, the current record is validated (name must not be blank) and if successful, changes made to the record are saved by the Framework and the newly selected record is shown.

Whilst editing a record, the user can press Esc to cancel changes. If they were creating a new record and they haven't yet entered a valid name and moved to another text box, the record is discarded by the Framewok.

The xml file is only updated when the form is closed as upadting the file after every record edit is most likely overkill.

The one extra thing you might want to do is to add Validated event handlers for the other text boxes and call EndEdit on the BindingSource.The DataGrid row would thenbe updated as they move from text box to text box.

Daniel B·  Saturday, July 12, 2008 10:36 PM

Hi steve1_rm,

I have to say that you have done a good job.

Based on my understanding, you want to add new person without using clear button when using DataBinding.

In the clear button click’s event handler, we know that the code is used to suspend the Data Binding and clear the text of the textbox. What we want is to place this code into another place.

In my opinion, we can achieve the goal by dealing with addNew button click’s event handler where we need to following steps:

1. Save the previous record.

2. Suspend the Data Binding of the BindingSource.

3. Clear the text of all the TextBox.

4. Call the AddNew method of BindingSource which will fire the AddingNew event of the BingdingSource.

Still, we need deal with the handler of AddingNew event in which we should resume the Data Binding. Note that before we clear the TextBox we should suspend Data Binding first.

Please feel free to contact me if you have further questions.

Best Regards,

Bruce Zhou

Bruce.Zhou  Wednesday, July 16, 2008 9:02 AM

You can use google to search for other answers

Custom Search

More Threads

• Save datagrid layout to file
• How to print table correct DataGrid? Help please for newbie!
• Add Data Source Not Working
• Binding to Radio Buttons in a Group Box
• Collection question
• DataGridView with objects
• Databinding two comboboxes to same source
• Spreadsheet in C#
• DataGridView and Scrolling via Mouse-Wheel
• complex search with calculated WHERE statement