Bind Grid View using Session in ASP.Net

HTML 
The following HTML Markup consists of an ASP.Net GridView along with some TextBoxes and a Button in order to insert data in GridView control.


<asp:GridView ID="GridView1" 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="Country" HeaderText="Country" 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">
            Country:<br />
            <asp:TextBox ID="txtCountry" runat="server" />
        </td>
    </tr>
    <tr>
        <td style="width: 100px">
            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
        </td>
    </tr>
</table>



Namespace

using System.Data;

Code


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("Country") });
        Session["
BindData
"
] = dt;
        this.BindGrid();
    }
}


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



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




Comments

Popular posts from this blog

Export HTML to PDF in Windows Forms Application using iTextSharp