Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Saturday, April 5, 2014

Save To Xml temporarily and then save to database

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h2>Save To Xml temporarily and then save to database</h2>
<div>
<table>
<tr>
<td style="width: 100px">
Name:</td>
<td style="width: 100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Location:</td>
<td style="width: 100px">
<asp:TextBox ID="txtLocation" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Email:</td>
<td style="width: 100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px" valign="top">
Comments:</td>
<td style="width: 100px">
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="104px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td>
</tr>
</table>
<br />
<asp:DataList ID="dlComments" Runat="server" Width="100%" OnItemCommand="dlComments_ItemCommand">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Id") %>' Visible="false"></asp:Label>
Name:
<asp:Label ID="lblName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "name") %>'></asp:Label><br />
E-mail: 
<a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%# DataBinder.Eval(Container.DataItem, "email") %></a>
<asp:Label ID="lblEmail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "email") %>' Visible="false"></asp:Label>  <br />
Location: 
<asp:Label ID="lblLocation" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "location") %>'></asp:Label><br />
Date: 
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Date") %>'></asp:Label><br />
Description: 
<asp:Label ID="lblDescription" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Description") %>'></asp:Label>
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Deletes" CommandArgument='<%#Eval("Id") %>'/>
</ItemTemplate>
</asp:DataList>
<br /><br /><br /><br /><br />
<asp:Button ID="btnSaveInDatabase" runat="server" Text="Save To database" OnClick="btnSaveInDatabase_Click"/>
</div>
</form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Xml;
using System.Data;
public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind xml data to datalist
            BindDatalist();
        }
    }
    /// <summary>
    /// btnSubmit event is used to insert data into XML file
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("Sample1.xml"));
        XmlElement parentelement = xmldoc.CreateElement("Comments");
        XmlElement Id = xmldoc.CreateElement("Id");
        Id.InnerText = Convert.ToString(Guid.NewGuid());
        XmlElement name = xmldoc.CreateElement("Name");
        name.InnerText = txtName.Text;
        XmlElement location = xmldoc.CreateElement("location");
        location.InnerText = txtLocation.Text;
        XmlElement email = xmldoc.CreateElement("Email");
        email.InnerText = txtEmail.Text;
        XmlElement Description = xmldoc.CreateElement("Description");
        Description.InnerText = txtComments.Text;
        XmlElement date = xmldoc.CreateElement("Date");
        date.InnerText = DateTime.Now.ToString();
        parentelement.AppendChild(Id);
        parentelement.AppendChild(name);
        parentelement.AppendChild(location);
        parentelement.AppendChild(email);
        parentelement.AppendChild(Description);
        parentelement.AppendChild(date);
        xmldoc.DocumentElement.AppendChild(parentelement);
        xmldoc.Save(Server.MapPath("Sample1.xml"));
        BindDatalist();
    }
    /// <summary>
    /// Bind xml data to datalist
    /// </summary>
    private void BindDatalist()
    {
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample1.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);
        xmlreader.Close();
        if (ds.Tables.Count != 0)
        {
            dlComments.DataSource = ds;
            dlComments.DataBind();
        }
        else
        {
            dlComments.DataSource = null;
            dlComments.DataBind();
        }
    }
    protected void dlComments_ItemCommand(object sender, CommandEventArgs e)
    {
        string ComamndName = e.CommandName;
        switch (ComamndName)
        {
            case "Deletes":
                Guid Id = new Guid(Convert.ToString(e.CommandArgument));
                //Add Delete Method here;
                deleteNode(Id);
                break;
        }
    }
    public void deleteNode(Guid Id)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("Sample1.xml"));
        foreach (XmlNode node in xmldoc.SelectNodes("CommentsInformation/Comments"))
        {
            if (node.SelectSingleNode("Id").InnerText == Id.ToString())
            {
                node.ParentNode.RemoveChild(node);
            }
        }
        xmldoc.Save(Server.MapPath("Sample1.xml"));
        BindDatalist();
    }
    protected void btnSaveInDatabase_Click(object sender, EventArgs e)
    {
        foreach (DataListItem item in dlComments.Items)
        {
            //We have already binded the values in the datalist in design page (Note:if u have not set - u can assign the values in OnItemDataBound event)
            Label lblId = (Label)item.FindControl("lblId");
            Label lblName = (Label)item.FindControl("lblName");
            Label lblEmail = (Label)item.FindControl("lblEmail");
            Label lblLocation = (Label)item.FindControl("lblLocation");
            Label lblDate = (Label)item.FindControl("lblDate");
            Label lblDescription = (Label)item.FindControl("lblDescription");
            string Id = lblId.Text;
            string Name = lblName.Text;
            string Email = lblEmail.Text;
            string Location = lblLocation.Text;
            string Date = lblDate.Text;
            string Description = lblDescription.Text;
            //write your save method here eg:
            //SaveToDb(Id, Name, Email, Location, Date, Description);
        }
    }
}


Sample1.xml
<?xml version="1.0" encoding="utf-8"?>
<CommentsInformation>
  <Comments>
    <Id>4fc979eb-c451-424d-960a-a2c99c834768</Id>
    <Name>Name1</Name>
    <location>NY</location>
    <Email>test@test.com</Email>
    <Description>test</Description>
    <Date>4/5/2014 7:47:50 PM</Date>
  </Comments>
  <Comments>
    <Id>5f3700d3-8247-47fb-ad27-7150922026c8</Id>
    <Name>Name2</Name>
    <location>India</location>
    <Email>test@test.com</Email>
    <Description>test</Description>
    <Date>4/5/2014 7:48:02 PM</Date>
  </Comments>
</CommentsInformation>


 



Gridview2

How to insert multiple rows into the GridView without using any database in ASP.NET using VB.NET/C# || how to save multiple rows in GridView into a Session.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   Username: <asp:TextBox ID="TextBox1" runat="server"/><br />
   Sitename: <asp:TextBox ID="TextBox2" runat="server"/><br />
   Facebook Id: <asp:TextBox ID="TextBox3" runat="server"/><br />
   Twitter Id: <asp:TextBox ID="TextBox4" runat="server"/><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:GridView ID="RGrid" runat="server" >
</asp:GridView>
    </div>
    </form>
</body>
</html>


Code for VB.NET:



Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Partial Public Class multiGrid
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub
    Private Sub BindGrid(ByVal rowcount As Integer)
        Dim dt As New DataTable()
        Dim dr As DataRow
  dt.Columns.Add(New System.Data.DataColumn("UserName", GetType([String])))
  dt.Columns.Add(New System.Data.DataColumn("Sitename", GetType([String])))
dt.Columns.Add(New System.Data.DataColumn("Facebook id", GetType([String])))
   dt.Columns.Add(New System.Data.DataColumn("Twitter id", GetType([String])))
        If Session("CurrentData") IsNot Nothing Then
            For i As Integer = 0 To rowcount
                dt = DirectCast(Session("CurrentData"), DataTable)
                If dt.Rows.Count > 0 Then
                    dr = dt.NewRow()
                    dr(0) = dt.Rows(0)(0).ToString()
                    dr(1) = dt.Rows(0)(1).ToString()
                    dr(2) = dt.Rows(0)(2).ToString()
                    dr(3) = dt.Rows(0)(3).ToString()
                End If
            Next
            dr = dt.NewRow()
            dr(0) = TextBox1.Text
            dr(1) = TextBox2.Text
            dr(2) = TextBox3.Text
            dr(3) = TextBox4.Text
            dt.Rows.Add(dr)
        Else
            dr = dt.NewRow()
            dr(0) = TextBox1.Text
            dr(1) = TextBox2.Text
            dr(2) = TextBox3.Text
            dr(3) = TextBox4.Text
            dt.Rows.Add(dr)
        End If
        ' If Session has a data then use the value as the DataSource
        If Session("CurrentData") IsNot Nothing Then
            RGrid.DataSource = DirectCast(Session("CurrentData"), DataTable)
            RGrid.DataBind()
        Else
            ' Bind GridView with the initial data assocaited in the DataTable
            RGrid.DataSource = dt
            RGrid.DataBind()
        End If
        ' Store the DataTable in Session to retain the values
        Session("CurrentData") = dt
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Check if the Session has a data assoiciated within it. If
        If Session("CurrentData") IsNot Nothing Then
            Dim dt As DataTable = DirectCast(Session("CurrentData"), DataTable)
            Dim count As Integer = dt.Rows.Count
            BindGrid(count)
        Else
            BindGrid(1)
        End If
    End Sub
End Class

Code for C#.NET:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class multiGrid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    private void BindGrid(int rowcount)
    {
        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new System.Data.DataColumn("UserName", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("Sitename", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("Facebook id", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("Twitter id", typeof(String)));
        if (Session["CurrentData"] != null)
        {
            for (int i = 0; i < rowcount + 1; i++)
            {
                dt = (DataTable)Session["CurrentData"];
                if (dt.Rows.Count > 0)
                {
                    dr = dt.NewRow();
                    dr[0] = dt.Rows[0][0].ToString();
                    dr[1] = dt.Rows[0][1].ToString();
                    dr[2] = dt.Rows[0][2].ToString();
                    dr[3] = dt.Rows[0][3].ToString();
                }
            }
            dr = dt.NewRow();
            dr[0] = TextBox1.Text;
            dr[1] = TextBox2.Text;
            dr[2] = TextBox3.Text;
            dr[3] = TextBox4.Text;
            dt.Rows.Add(dr);
        }
        else
        {
            dr = dt.NewRow();
            dr[0] = TextBox1.Text;
            dr[1] = TextBox2.Text;
            dr[2] = TextBox3.Text;
            dr[3] = TextBox4.Text;
            dt.Rows.Add(dr);
        }
        // If Session has a data then use the value as the DataSource
        if (Session["CurrentData"] != null)
        {
            RGrid.DataSource = (DataTable)Session["CurrentData"];
            RGrid.DataBind();
        }
        else
        {
            // Bind GridView with the initial data assocaited in the DataTable
            RGrid.DataSource = dt;
            RGrid.DataBind();
        }
        // Store the DataTable in Session to retain the values
        Session["CurrentData"] = dt;
    }
      protected void Button1_Click(object sender, EventArgs e)
    {
        // Check if the Session has a data assoiciated within it. If
        if (Session["CurrentData"] != null)
        {
            DataTable dt = (DataTable)Session["CurrentData"];
            int count = dt.Rows.Count;
            BindGrid(count);
        }
        else
        {
            BindGrid(1);
        }
    
    }
}


Output:



Gridview1