Article

How to Bind Data to GridView Control using Session in ASP.Net

20 Jun 2018 Kamal Pratap
0 Comments 704 Views



Here we will explain how to bind data to GridView Control using session in ASP.Net C#. Many times we need to use this scenario to perform some task for example

 

We have to develope a ecommerce website and we have a requirement to create the shopping cart using session then below code can help us to manages these cases. First we will create the DataTable to store shopping cart value and then store the DataTable into session. Further we can display the shopping cart  to bind data to GridView control using session.

<asp:GridView ID="grdCustomer" runat="server" CssClass="Grid" AutoGenerateColumns="false"
    EmptyDataText="No records has been added.">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Address" HeaderText="Address" ItemStyle-Width="120" />
    </Columns>
</asp:GridView>
<br />
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
    <tr>
        <td style="padding-bottom: 10px">
            Name:<br />
            <asp:TextBox ID="txtName" runat="server" />
        </td>
    </tr>
    <tr>
        <td style="padding-bottom: 10px">
            Address:<br />
            <asp:TextBox ID="txtAddress" runat="server" />
        </td>
    </tr>
    <tr>
        <td style="width: 100px">
            <asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
        </td>
    </tr>
</table>

On page load event

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Address") });
        Session["Customers"] = dt;
        this.BindGrid();
    }
}

protected void BindGrid()
{
    grdCustomer.DataSource = (DataTable)Session["Customers"];
    grdCustomer.DataBind();
}

On Add button click

protected void btnAdd_Click(object sender, EventArgs e)
{
    DataTable dt = (DataTable)Session["Customers"];
    dt.Rows.Add(txtName.Text.Trim(), txtAddress.Text.Trim());
    Session["Customers"] = dt;
    this.BindGrid();
    txtName.Text = string.Empty;
    txtAddress.Text = string.Empty;
}

 

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

No coments found to display!

Leave a Comment