Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Adding and Removing Records from DataSet/XML and Populate Grid using ASP.NET and C#

In this article you will see another way in how add and remove data from XML, display it in DataGrid and saving it back into XML.

In earlier tutorial we discuss about the retrieving data from XML, displaying it in DataGrid and then adding and deleting data in XML document and saving it back into XML. There are other simple methods to do the same. The C# provides a powerful feature called dataset. You can read the whole XML in dataset, perform different operation and save it back to XML.

This article will cover the following topics:

  1. Read XML into DataSet
  2. Write DataSet into XML
  3. Add data in DataSet
  4. Delete data from DataSet
 Application UI with Data

Figure 1: Application UI with Data

XML Data:

To demonstrate the above functionality, let’s take an example of subjects. Each subject has few characteristics like ID, Name, Chapters, and Exams.

The below is a sample XML. This XML shall be used during this demonstration.

Listing 1: XML Data

<?xml version="1.0" standalone="yes"?>
<Subjects>
  <Subject>
    <ID>1</ID>
    <Name>Math's</Name>
    <Chapters>10</Chapters>
    <Exams>5</Exams>
  </Subject>
  <Subject>
    <ID>2</ID>
    <Name>English</Name>
    <Chapters>5</Chapters>
    <Exams>5</Exams>
  </Subject>
  <Subject>
    <ID>3</ID>
    <Name>Physics</Name>
    <Chapters>8</Chapters>
    <Exams>4</Exams>
  </Subject>
</Subjects>

ASP.NET Code:

The below is the ASP.NET Page code, which is having 4 ASP textboxes - ID, Name, Chapters, Exams. The page also has two buttons to Add and Delete the subject. At the end there is a DataGrid to show all XML data.

Also have an error label to show interactive messages while program execution.

Listing 2: ASP.NET Script

<head runat="server">
    <title>MrBool.com ASP.NET and C# Tutorials - GidView, XML and DataSet</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Subject  ID:
                </td>
                <td>
                    <asp:TextBox ID="txtSubjectID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Subject Name:
                </td>
                <td>
                    <asp:TextBox ID="txtSubjectName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Subject Chapters:
                </td>
                <td>
                    <asp:TextBox ID="txtSubjectChapters" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Subject Exams:
                </td>
                <td>
                    <asp:TextBox ID="txtSubjectExams" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label runat="server" ID="lblError" Font-Bold="true" ForeColor="Red"></asp:Label>
                </td>
            </tr>
        </table>
        <br />
        <asp:Button ID="btnAddSubject" runat="server" Text="Add Subject" OnClick="btnAddSubject_Click" />
        <asp:Button ID="btnRemoveSubject" runat="server" Text="Remove Subject" OnClick="btnRemoveSubject_Click" />
        <br />
        <br />
        <br />
        <asp:DataGrid ID="dgSubjects" runat="server" AutoGenerateColumns="true">
            <HeaderStyle Font-Bold="true" />
        </asp:DataGrid>
        <br />
    </div>
    </form>
</body>

C# Code:

You have to add the fowling namespaces to run this program:

Listing 3: Namespace used

using System.Xml;
using System.Drawing; 

This C# program is organized through methods and events.

In page load event populate the DataGrid. As you know that the program has a label to show messages and messages are of different colors, so also maintaining the color and visibility in this section.

 Blank field notification

Figure 2: Blank field notification

Listing 4: Page_Load Event

protected void Page_Load(object sender, EventArgs e)
    {
        lblError.Visible = false;
        lblError.ForeColor = Color.Red;
        if (!IsPostBack)
            PopulateGrid();
    }

The below section read the XML in DataSet and return it for further use.

Listing 5: ReadSubjectDataSet

private DataSet ReadSubjectDataSet()
    {
        DataSet oDs = new DataSet();

        oDs.ReadXml(Server.MapPath(strXMLFileName));
        return oDs;
    }

The below section is counterpart of ReadSubjectDataSet, SaveSubjectDataSet write the dataset into XML

Listing 6: SaveSubjectDataSet

private void SaveSubjectDataSet(DataSet oDs)
    {
        if (oDs != null)
            oDs.WriteXml(Server.MapPath(strXMLFileName));
    }

To populate the grid with XML data, the below section get dataset and bind to grid.

Listing 7: PopulateGrid

private void PopulateGrid()
    {
        DataSet oDs = ReadSubjectDataSet();
        if (oDs != null && oDs.Tables.Count > 0 && oDs.Tables[0].Rows.Count > 0)
        {
            dgSubjects.DataSource = oDs;
            dgSubjects.DataBind();
        }
    }

Add Record to DataSet:

New Subject Added - Chemistry

Figure 3: New Subject Added - Chemistry

Let’s start discussing the add data. First check if all the textbox are filled otherwise display a message and bypass all code execution. If textboxes are filled then read the dataset and check if datatable is there.

Now copy the structure of datarow and create a new datarow, Note that datarow has columns and their data types inside, so we have to copy the structure.

DataRow oDr = oDs.Tables[0].NewRow();

Now fill the data in datarow:

oDr["ID"] = txtSubjectID.Text;

Now add datarow in datatable

oDs.Tables[0].Rows.Add(oDr);

Don't forget to commit the changes otherwise you will lose data

oDs.AcceptChanges();

Now save the dataset in XML and repopulate the grid.

Listing 8: Add Subject

protected void btnAddSubject_Click(object sender, EventArgs e)
    {
        //Add only if data is there
        if (txtSubjectID.Text.Trim() != "" && txtSubjectName.Text.Trim() != "" && txtSubjectChapters.Text.Trim() != "" && txtSubjectExams.Text.Trim() != "")
        {
            DataSet oDs = ReadSubjectDataSet();
            //Check if table exist
            if (oDs != null && oDs.Tables.Count > 0)
            {
                //Copy the structue of row and fill data
                DataRow oDr = oDs.Tables[0].NewRow();
                oDr["ID"] = txtSubjectID.Text;
                oDr["Name"] = txtSubjectName.Text;
                oDr["Chapters"] = txtSubjectChapters.Text;
                oDr["Exams"] = txtSubjectExams.Text;

                //Add Row to datatable
                oDs.Tables[0].Rows.Add(oDr);

                //Commit the changes
                oDs.AcceptChanges();
                //Save the changes
                SaveSubjectDataSet(oDs);
                PopulateGrid();

                lblError.Visible = true;
                lblError.ForeColor = Color.Green;
                lblError.Text = "Record added successfully.";
            }

        }
        else
        {
            lblError.Visible = true;
            lblError.Text = "Please fill all the subject fields before Add";
        }
    }

Delete Record From DataSet:

Subject Deleted - English

Figure 4: Subject Deleted - English

To delete a record from dataset, just loop through all the rows of dataset/datatable and match with the textbox value

oDs.Tables[0].Rows[counter]["Name"].ToString() == txtSubjectName.Text

If matching perfectly delete the row

oDs.Tables[0].Rows[counter].Delete();

After deleting commit changes and save the dataset in XML and repopulate the grid.

Listing 9: Remove Subject

protected void btnRemoveSubject_Click(object sender, EventArgs e)
    {
        //Add only if data is there
        if (txtSubjectName.Text.Trim() != "")
        {
            DataSet oDs = ReadSubjectDataSet();
            //Check if table exist
            if (oDs != null && oDs.Tables.Count > 0)
            {
                //loop through all the rows
                for (int counter = 0; counter < oDs.Tables[0].Rows.Count; counter++)
                {
                    //Find the correct row
                    if (oDs.Tables[0].Rows[counter]["Name"] != null && oDs.Tables[0].Rows[counter]["Name"].ToString() == txtSubjectName.Text)
                    {
                        //Delete the row
                        oDs.Tables[0].Rows[counter].Delete();
                        break;
                    }
                }
                //Commit the changes
                oDs.AcceptChanges();
                //Save the changes
                SaveSubjectDataSet(oDs);
                PopulateGrid();

                lblError.Visible = true;
                lblError.ForeColor = Color.Green;
                lblError.Text = "Record deleted successfully.";
            }

        }
        else
        {
            lblError.Visible = true;
            lblError.Text = "Please fill all the subject name before Delete";
        }

    }


I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login