articles

Home / DeveloperSection / Articles / CRUD Operation using XSD Dataset in C#

CRUD Operation using XSD Dataset in C#

CRUD Operation using XSD Dataset in C#

Chris Anderson 34894 21-Jan-2013

CRUD Operation using XSD Dataset in C#

Hi Friends, Today In this article I am going to explain how to use XSD Dataset to read and write data in XML format using c# in win forms.

By the using of Ado.NET, you can fill a Dataset from an XML stream or document. When You can use the XML stream or document to supply the Dataset either data, schema information, or both. Then the information supplied from the XML stream or document can be combined with existing data or schema information already present in the DataSet.

Here, the following example demonstrates how to create a Customer Entry Form using the XSD dataset. We are saving customer data in the XML file (Customer.xml) and also using LINQ to find the records of the customer.

Before creating the following application, do the following steps :

Create a new Windows application using Microsoft Visual C#.

Design a Customer entry form as shown in below screenshot :

CustomerID field is read-only because it will be auto-generated.

Add some default countries in the Country Combobox, as given below:

Design a Customer Search form

(1).  Make Done button DialogResult property to OK and Cancel button DialogResult property to Cancel.

(2).  Name the textbox as txtCutomerId.

Create a property CustomerID and bind it to Textbox Text property. Code is given below:

        public event PropertyChangedEventHandler PropertyChanged;

        private int customerId;
        public int CustomerId
        {
            get
            {                 return customerId;
            }
            set
            {
                customerId = value;
                InvokePropertyChanged(new PropertyChangedEventArgs("CustomerID"));
            }
        }
        public void InvokePropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)             {
                handler(this, e);
            }
        }
        private void Search_Load(object sender, EventArgs e)
        {
            txtCutomerId.DataBindings.Add("Text", this, "CustomerId");
        }

 To prevent blank entry in CustomerID textbox, add the following code on Form Closing event of Search form:

private void Search_FormClosing(object sender, FormClosingEventArgs e)

{
            if (DialogResult == DialogResult.OK)
            {                 if (string.IsNullOrEmpty(txtCutomerId.Text.Trim()))
                {
                    MessageBox.Show("Please enter customer Id", "Search", MessageBoxButtons.OK, MessageBoxIcon.Error);                     e.Cancel = true;
                }
            }
}

 To add a dataset

  • Got to Project -> Add New Item.
  • Select Data from the Installed Templates.
  • Select DataSet -> Enter CustomerDS.xsd in Name textbox.

Add a New DataTable (Customer) in the dataset as shown in the below screenshot and set the CustomerID as primary key and its data type to System.Int32.

Change the data type of column DateofBirth to DateTime. 

Add the following methods in your Customer form:

This method (GetNewCustomerID) will always return a new CustomerID:

private int GetNewCustomerID()

{
       int max = dtCustomer.Rows.Count > 0 ? (from dt in dtCustomer select dt.CustomerID).Max() + 1 : 1;
       return max; }

 The method (SetCustomer) sets the customer data into the form fields. For this, we have to pass the customer row as a parameter.

private void SetCustomer(CustomerDS.CustomerRow customer)

{
      txtCustomerID.Text = customer.CustomerID.ToString();
      txtName.Text = customer.Name;
      cmbCountry.Text = customer.Country;
      dtDob.Value = customer.DateofBirth;
      txtZipCode.Text = customer.ZipCode;
}

 This method (ResetCustomer) reset the form fields after saving the data.

private void ResetCustomer()

{
      txtName.Text = string.Empty;
      cmbCountry.SelectedItem = null;
      dtDob.Value = DateTime.Now;
      txtZipCode.Text = string.Empty;
      int customerId = GetNewCustomerID();
      txtCustomerID.Text = customerId.ToString();
 }

 Create a new object of Customer DataTable at the class level:

CustomerDS.CustomerDataTable dtCustomer = new CustomerDS.CustomerDataTable();

 On the form, load read the XML file (Customer.xml) if it exists and set the new customer id by using the GetNewCustomerID method.

private void Customer_Load(object sender, EventArgs e)

{
      if (System.IO.File.Exists("Customer.xml"))
           dtCustomer.ReadXml("Customer.xml");
      int customerId = GetNewCustomerID();
      txtCustomerID.Text = customerId.ToString();
}

 On the click of the save button add the following code. It will add the customer if the CustomerID does not exist otherwise update the data of the customer on the basis of CustomerID.

private void btnSave_Click(object sender, EventArgs e)

{
            int customerId = int.Parse(txtCustomerID.Text);
            CustomerDS.CustomerRow row = dtCustomer.Rows.Find(customerId) as CustomerDS.CustomerRow;
            if (row == null)
            {
                row = dtCustomer.NewCustomerRow();
                row.CustomerID = customerId;
                dtCustomer.AddCustomerRow(row);
            }
            row.Name = txtName.Text.Trim();
            row.Country = cmbCountry.Text;
            row.DateofBirth = dtDob.Value;
            row.ZipCode = txtZipCode.Text.Trim();
            dtCustomer.AcceptChanges();
            dtCustomer.WriteXml("Customer.xml");
            MessageBox.Show("Record saved successfully", "Customer", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ResetCustomer();
 }

 To delete the customer record, add the following on the click of the Delete button.

private void btnDelete_Click(object sender, EventArgs e)

{
            int customerId = int.Parse(txtCustomerID.Text);
            CustomerDS.CustomerRow row = dtCustomer.Rows.Find(customerId) as CustomerDS.CustomerRow;
            if (row != null)
            {
                row.Delete();
                dtCustomer.AcceptChanges();
                dtCustomer.WriteXml("Customer.xml");
                MessageBox.Show("Record deleted successfully", "Customer", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
 }

 To search a customer, paste the given code on the click event of Search button:

private void btnSearch_Click(object sender, EventArgs e)

{
            Search search = new Search();
            DialogResult dr = search.ShowDialog();
            if (dr == DialogResult.OK)
            {
                CustomerDS.CustomerRow row = dtCustomer.Rows.Find(search.CustomerId) as CustomerDS.CustomerRow;
                if (row != null)
                {
                    SetCustomer(row);
                }
            }
 }

 To find the first record from the DataTable:

private void btnFirst_Click(object sender, EventArgs e)

{
      CustomerDS.CustomerRow row = dtCustomer.FirstOrDefault();
      if (row != null)
      {
          SetCustomer(row);
      }
}

 To find the next record from the DataTable:

private void btnNext_Click(object sender, EventArgs e)

{
       int customerId = int.Parse(txtCustomerID.Text);
       CustomerDS.CustomerRow row = (from dt in dtCustomer
         where dt.CustomerID > customerId
         orderby dt.CustomerID ascending
         select dt).FirstOrDefault() as CustomerDS.CustomerRow;
        if (row != null)
        {
           SetCustomer(row);
        }
}

 To find the previous record from the DataTable:

private void btnPrevious_Click(object sender, EventArgs e)

{
            int customerId = int.Parse(txtCustomerID.Text);
            CustomerDS.CustomerRow row = (from dt in dtCustomer
             where dt.CustomerID < customerId
             orderby dt.CustomerID descending
             select dt).FirstOrDefault() as CustomerDS.CustomerRow;
            if (row != null)
            {
                SetCustomer(row);
            }
 }

 To find the last record from the DataTable:

private void btnLast_Click(object sender, EventArgs e)

{
       CustomerDS.CustomerRow row = dtCustomer.LastOrDefault();
       if (row != null)        {
          SetCustomer(row);
       }
 }

 Now run or debug this application to see the output. You need to add some records in order to test it properly:

 After adding some records you can also search records on the basis of CustomerID by using Search form.

The data will be saved in the XML file (Customer.xml) in given format:

Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.


You may also read this Article - Expandable and Collapsible Rows in Datagrid in C# Winforms


c# c# 
Updated 14-Dec-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By