Saturday, April 7, 2012

Save the data into xml and display in gridview in asp.net



.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Request.MapPath("XMLFile.xml"));
            grvProducts.DataSource = ds.Tables[0];
            grvProducts.DataBind();
            ViewState["dtProducts"] = ds.Tables[0];
        }
    }   
    protected void btnSave_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)ViewState["dtProducts"];       
        dt.Rows.Add(txtPName.Text, txtPrice.Text, txtqty.Text, Convert.ToDateTime(txtSdate.Text).ToShortDateString());
        dt.AcceptChanges();
        dt.WriteXml(Request.MapPath("XMLFile.xml"));       
       
        grvProducts.DataSource = dt;
        grvProducts.DataBind();
    }



.aspx


  <table>
        <tr>
          <td>
            Product Name :
          </td>
           <td>
             <asp:TextBox ID="txtPName" runat="server"></asp:TextBox>
          </td>
        </tr>
         <tr>
           <td>
            Price :
          </td>
           <td>
             <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox>
          </td>
        </tr>
          <tr>
           <td>
            Quantity :
          </td>
           <td>
             <asp:TextBox ID="txtqty" runat="server"></asp:TextBox>
          </td>
        </tr>
          <tr>
           <td>
            Sale Date :
          </td>
           <td>
             <asp:TextBox ID="txtSdate" runat="server"></asp:TextBox>
          </td>
        </tr>
         <tr>
           <td>
           Total Price :
          </td>
           <td>
             <asp:Label ID="lblPrice" runat="server"></asp:Label>
          </td>
        </tr>
         <tr>          
           <td colspan="2">
             <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
          </td>
        </tr>
      </table>
      <br />
      <asp:GridView ID="grvProducts" runat="server" AutoGenerateColumns="true">
       
      </asp:GridView>



XMLFile.xml


<?xml version="1.0" standalone="yes"?>
<DocumentElement>
  <Product id="1">
    <Name>Test</Name>
    <Price>2000</Price>
    <Qty>2</Qty>
    <Date>12/2/2010</Date>
  </Product> 
  <Product>
    <Name>Mobile</Name>
    <Price>6500</Price>
    <Qty>3</Qty>
    <Date>5/9/2010</Date>
  </Product>
</DocumentElement>

No comments:

Post a Comment

Comments

Search

Custom Search
Protected by Copyscape Plagiarism Software