Create DataTable and store data in datatable and bind with gridview

Here we bind the gridview without using database I.e we use the Datatable for storing data for a specific period of time and we use that data table for binding the gridview.

First we create a datatable. Follow the below code.

Namespace for Datatable,
Using system.Data.Sqlclient;
Using system.Data;

Then write the method for create datatable. 

 private void temptable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ItemDetail_ID", typeof(int));
            dt.Columns.Add("Item_Price", typeof(string));
            dt.Columns.Add("Item_Barcode", typeof(string));
            dt.Columns.Add("Quantity", typeof(string));
            dt.Columns.Add("image", typeof(string));
            Session["dt"] = dt;
            BindGrid();
        }

Then call this above method in page load.

Then write another method for bind Gridview. Follow the below method,

protected void BindGrid()
{
gvattributes.DataSource = Session["dt"] as DataTable;
gvattributes.DataBind();
}

Then call this method in page load.

Then for saving Data in DataTable on button click. Follow the below code.

protected void btnSave_Click(object sender, EventArgs e)
{
DataTable dt=Session["dt"] as DataTable;
dr = dt.NewRow();
dr["ItemDetail_ID"]= txtItemDetail_ID.Text.ToString();
dr["Item_Price"] = txtItem_Price.Text;
dr["Item_Barcode"] = txtItem_BarCode.Text;
dr["Quantity"] = txtQuantity.Text;
dr["image"] = txtItemDetail_ID.Text.ToString();
Session["dt"] = dt;
BindGrid();
}
Related Links:


Post a Comment

0 Comments