Home  


Add a Dataset Records in ADO.NET

To create a new record, the user will fill in the fields and press the New button. This will fire the btnNew_Click event, which is tied to the btnNew_Click event handling method. In the event handler, call DataTable.NewRow( ), which asks the table for a new DataRow object. This is very elegant because the new row that the DataTable produces has all the necessary DataColumns for this table. You can just fill in the columns you care about, taking the text from the user interface (UI). Now that the row is fully populated, just add it back to the table. The table resides within the DataSet, so all you have to do is tell the DataAdapter object to update the database with the DataSet and accept the changes. Next, update the user interface, you can now repopulate the list box with your new added row and clear the text fields so that you're ready for another new record.

// **** Handle the ADD button click
protected void btnAdd_Click (object sender, System.EventArgs e)
{
    // Create a new row, populate it with entered
    // Data from the ListBox
    DataRow newRow = _dataTable.NewRow();
    newRow["CustomerID"]   = txtCompanyID.Text;
    newRow["CompanyName"]  = txtCompanyName.Text;
    newRow["ContactName"]  = txtContactName.Text;
    newRow["ContactTitle"] = txtContactTitle.Text;
    newRow["Address"]      = txtAddress.Text;
    newRow["City"]         = txtCity.Text;
    newRow["PostalCode"]   = txtZip.Text;
    newRow["Phone"]        = txtPhone.Text;

    // Add the new row to the table in the dataset
    _dataTable.Rows.Add(newRow);

    // Update the database, any Error is catched in catch block
    try
    {
        // Prepared UPDATE Command is executed
        _dataAdapter.Update(_dataSet,"Customers");
        _dataSet.AcceptChanges();

        // Inform the user and repaint Form
        lblMessage.Text = "Updated!";
        Application.DoEvents();

        // Repopulate the list box
        PopulateListBox();

        // Clear all the text fields
        ClearFields();
    }
    catch (SqlException ex)
    {
        _dataSet.RejectChanges();
        MessageBox.Show(ex.Message);
    }
}