locked
want to detete entries in gridview view state? RRS feed

  • Question

  • User-1647172364 posted

    hello in my code i want to use grid view view state and when i clicked on generate button and add entries in the view state  i want to delete these entries clicked on another submit button this is not save the data in the database this is static base where entries display in view state those were deleted

    here is my code

    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace Store
    {
        public partial class RemovePurchaseBarcode : System.Web.UI.Page
        {
    
    
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    AddDefaultFirstRecord();
    
                }
            }
    
    
    
            private void AddDefaultFirstRecord()
            {
                // creating dataTable
                DataTable dt = new DataTable();
    
                dt.TableName = "tbl_products";
                dt.Columns.Add(new DataColumn("barcode", typeof(string)));
    
                //saving databale into viewstate 
                ViewState["tbl_products"] = dt;
                //bind Gridview 
                Gv1.DataSource = dt;
                Gv1.DataBind();
            }
    
            private void AddNewRecordRowToGrid()
            {
                // check view state is not null 
                if (ViewState["tbl_products"] != null)
                {
                    //get datatable from view state 
                    DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
    
                    //add data to datatable
                    DataRow drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["barcode"] = txtBarcode.Text;
    
                    //add created Rows into dataTable 
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    //Save Data table into view state after creating each row 
                    ViewState["tbl_products"] = dtCurrentTable;
                    //Bind Gridview with latest Row 
                    Gv1.DataSource = dtCurrentTable;
                    Gv1.DataBind();
    
                }
            }
            // Add the Cross header when the row count is greater than 0
            //protected void GridView1_DataBound(object sender, EventArgs e)
            //{
            //    GridView gv = (GridView)sender;
    
            //    if (gv != null)
            //    {
            //        if (gv.Rows.Count > 0)
            //        {
            //            // The row to be added as the header container
            //            GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
    
            //            // The cross header
            //            TableCell crossHeader = new TableHeaderCell();
            //            crossHeader.ColumnSpan = gv.Columns.Count;
            //            crossHeader.Text = "Cross Header";
    
            //            row.Cells.Add(crossHeader);
    
            //            // Get the table of the grid view and add the row on the top
            //            Table t = gv.Controls[0] as Table;
            //            if (t != null)
            //            {
            //                t.Rows.AddAt(0, row);
            //            }
            //        }
            //    }
            //}
    
            protected void GenerateBarcode(object sender, EventArgs e)
            {
                AddNewRecordRowToGrid();
            }
    
    
    
            protected void btn_Click(object sender, EventArgs e)
            {
                foreach (GridViewRow row in Gv1.Rows)
                {
                    string temp1 = row.Cells[0].Text;
                    //es
                    //delete from tbl_master where temp1=temp1;
                    //pa temp1;
                    //close
    
                    using (storeEntities3 ctx = new storeEntities3())
                    {
                        var cust = (from a in ctx.tbl_products
                                    where a.barcode == temp1
                                    select a).FirstOrDefault();
    
                        if (cust != null)
                        {
                            ctx.tbl_products.Remove(cust);
                            ctx.SaveChanges();
                        }
                    }
    
                }
            }
        }
    }
    
    Aspx
    
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RemovePurchaseBarcode.aspx.cs" Inherits="Store.RemovePurchaseBarcode" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="title" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="server">
        
        <div class="container-fluid">
           
                       <h3 style="color:black; font-size:2.8em">Remove Purchase Barcode</h3>    
                       <hr />
    
       <div class="row">
           <div class="col-sm-6">
     <asp:TextBox ID="txtBarcode" runat="server" class="form-control" Width="220px"></asp:TextBox><br />
    <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="GenerateBarcode" class="btn btn-primary" />
    
           </div>
    </div>
    <asp:Image ID="imgBarcode" runat="server" Visible="false"  />
        <br /><br />
                   <% if (Gv1.Rows.Count == 0)
                    { %>
                <div class="card border-primary mb-3" style="width:100%">
                    <div class="card-header">Sorry, No Data</div>
               <%--     <div class="card-body text-primary">
                        <h5 class="card-title">Sorry, No Data</h5>
                        <p class="card-text">Please add product information.</p>
                    </div>--%>
                </div>
                <% } %>
          <asp:GridView runat="server" AutoGenerateColumns="False"  ID="Gv1" BackColor="#0063A4"  BorderColor="#999999" HeaderStyle-ForeColor="White" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" CellSpacing="1"  Width="100%"> 
                                <AlternatingRowStyle HorizontalAlign="Justify" Wrap="False"  />
                   
                <Columns>
    
    <asp:BoundField DataField="barcode" HeaderText="Barcode" HeaderStyle-ForeColor="White" />
    
    
     
              
    
                        </Columns>
                                <FooterStyle BackColor="#CCCCCC" />
                                <HeaderStyle BackColor="Transparent"   Font-Bold="True" ForeColor="Black" />
                                <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                                <RowStyle BackColor="White" />
                                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                                <SortedAscendingHeaderStyle BackColor="#808080" />
                                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                                <SortedDescendingHeaderStyle BackColor="#383838" />
                        </asp:GridView>
    
    
        
        
     <asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" class="btn btn-primary" />
    
        
        
        
        </div>
    </asp:Content>
        
    
    
    
    

    Wednesday, September 16, 2020 6:01 AM

Answers

  • User-939850651 posted

    Hi sanam13,

    I don't know what you are doing now that caused the problem. In my test, it works correctly:

    truncate table tbl_products
    
    insert into tbl_products (product_name,uom,mrp,barcode) values 
    ('product_name1','uom1','mrp1','aaa'),
    ('product_name2','uom2','mrp2','ccc'),
    ('product_name3','uom3','mrp3','ddd'),
    ('product_name4','uom4','mrp4','eee'),
    ('product_name5','uom5','mrp5','ggg')
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    AddDefaultFirstRecord();
    
                }
            }
    
            private void AddDefaultFirstRecord()
            {
                // creating dataTable
                DataTable dt = new DataTable();
    
                dt.TableName = "tbl_products";
                dt.Columns.Add(new DataColumn("barcode", typeof(string)));
    
                //saving databale into viewstate 
                ViewState["tbl_products"] = dt;
                //bind Gridview 
                Gv1.DataSource = dt;
                Gv1.DataBind();
            }
    
            private void AddNewRecordRowToGrid()
            {
                // check view state is not null 
                if (ViewState["tbl_products"] != null)
                {
                    //get datatable from view state 
                    DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
    
                    //add data to datatable
                    DataRow drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["barcode"] = txtBarcode.Text;
    
                    //add created Rows into dataTable 
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    //Save Data table into view state after creating each row 
                    ViewState["tbl_products"] = dtCurrentTable;
                    //Bind Gridview with latest Row 
                    Gv1.DataSource = dtCurrentTable;
                    Gv1.DataBind();
                }
            }
    
            protected void GenerateBarcode(object sender, EventArgs e)
            {
                AddNewRecordRowToGrid();
            }
    
            protected void btn_Click(object sender, EventArgs e)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
                foreach (GridViewRow row in Gv1.Rows)
                {
                    string temp1 = row.Cells[0].Text;
                    //es
                    //delete from tbl_master where temp1=temp1;
                    //pa temp1;
                    //close
    
                    using (storeEntities ctx = new storeEntities())
                    {
                        var cust = (from a in ctx.tbl_products
                                    where a.barcode == temp1
                                    select a).FirstOrDefault();
    
                        if (cust != null)
                        {
                            ctx.tbl_products.Remove(cust);
                            ctx.SaveChanges();
                            //remove existing records in ViewState
                            dtCurrentTable.Rows.Remove(dtCurrentTable.Select("barcode = '" + temp1 + "'")[0]);
                            ViewState["tbl_products"] = dtCurrentTable;
                        }
                    }
                }
                Gv1.DataSource = dtCurrentTable;
                Gv1.DataBind();
            }
    <body>
        <form id="form1" runat="server">
            <div class="container-fluid">
                <h3 style="color: black; font-size: 2.8em">Remove Purchase Barcode</h3>
                <hr />
                <div class="row">
                    <div class="col-sm-6">
                        <asp:TextBox ID="txtBarcode" runat="server" class="form-control" Width="220px"></asp:TextBox><br />
                        <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="GenerateBarcode" class="btn btn-primary" />
                    </div>
                </div>
                <asp:Image ID="imgBarcode" runat="server" Visible="false" />
                <br />
                <br />
                <% if (Gv1.Rows.Count == 0)
                    { %>
                <div class="card border-primary mb-3" style="width: 100%">
                    <div class="card-header">Sorry, No Data</div>
                    <%--     <div class="card-body text-primary">
                        <h5 class="card-title">Sorry, No Data</h5>
                        <p class="card-text">Please add product information.</p>
                    </div>--%>
                </div>
                <% } %>
                <asp:GridView runat="server" AutoGenerateColumns="False" ID="Gv1" BackColor="#0063A4" BorderColor="#999999" HeaderStyle-ForeColor="White" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" CellSpacing="1" Width="100%">
                    <AlternatingRowStyle HorizontalAlign="Justify" Wrap="False" />
                    <Columns>
                        <asp:BoundField DataField="barcode" HeaderText="Barcode" HeaderStyle-ForeColor="White" />
                    </Columns>
                    <FooterStyle BackColor="#CCCCCC" />
                    <HeaderStyle BackColor="Transparent" Font-Bold="True" ForeColor="Black" />
                    <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                    <RowStyle BackColor="White" />
                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#F1F1F1" />
                    <SortedAscendingHeaderStyle BackColor="#808080" />
                    <SortedDescendingCellStyle BackColor="#CAC9C9" />
                    <SortedDescendingHeaderStyle BackColor="#383838" />
                </asp:GridView>
                <asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" class="btn btn-primary" />
            </div>
        </form>
    </body>

    Result:

    It can be clearly seen that there are no two records, bbb and fff, in the database table, so they are retained.

    Please use a debugging tool to find the cause of the problem, and then try to solve it.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 17, 2020 8:27 AM

All replies

  • User-939850651 posted

    Hi sanam13,

    According to your description, I checked and tested your code, and I found that the data source of the GridView in the page comes from ViewState instead of the data read from the database table.

    Therefore, when you delete the records in the database table, it will not have any impact on ViewState. You need to update the ViewState accordingly while operating the database table.

    Just do something like this:

    protected void btn_Click(object sender, EventArgs e)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
                foreach (GridViewRow row in Gv1.Rows)
                {
                    string temp1 = row.Cells[0].Text;
                    //es
                    //delete from tbl_master where temp1=temp1;
                    //pa temp1;
                    //close
    
                    using (storeentities3 ctx = new storeentities3())
                    {
                        var cust = (from a in ctx.tbl_products
                                    where a.barcode == temp1
                                    select a).firstordefault();
    
                        if (cust != null)
                        {
                            ctx.tbl_products.remove(cust);
                            ctx.savechanges();
                            // remove existing records in ViewState
                            dtCurrentTable.Rows.Remove(dtCurrentTable.Select("barcode = '" + temp1 + "'")[0]);
                            ViewState["tbl_products"] = dtCurrentTable;
                        }
                    }
                }
                Gv1.DataSource = dtCurrentTable;
                Gv1.DataBind();
            }

    If I misunderstood something, please let me know.

    Best regards,

    Xudong Peng

    Wednesday, September 16, 2020 8:59 AM
  • User-1647172364 posted

    Sir i have applied ur given code but not working gridview view state entries were not deleted as i expected.

    Wednesday, September 16, 2020 10:20 AM
  • User-939850651 posted

    Hi sanam13,

    Sir i have applied ur given code but not working gridview view state entries were not deleted as i expected.

    The content in the GridView on the page has not changed? If this is the case, try to rebind the data source for the GridView.

    This is my oversight. I did not mark this part in the code given above.

         Gv1.DataSource = dtCurrentTable;
         Gv1.DataBind();

    Best regards,

    Xudong Peng

    Thursday, September 17, 2020 2:21 AM
  • User-1647172364 posted

    Sir pls provide me correct code so that i can implement in my page.

    Thursday, September 17, 2020 5:56 AM
  • User-939850651 posted

    Hi sanam13,

    I don't know what you are doing now that caused the problem. In my test, it works correctly:

    truncate table tbl_products
    
    insert into tbl_products (product_name,uom,mrp,barcode) values 
    ('product_name1','uom1','mrp1','aaa'),
    ('product_name2','uom2','mrp2','ccc'),
    ('product_name3','uom3','mrp3','ddd'),
    ('product_name4','uom4','mrp4','eee'),
    ('product_name5','uom5','mrp5','ggg')
    protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    AddDefaultFirstRecord();
    
                }
            }
    
            private void AddDefaultFirstRecord()
            {
                // creating dataTable
                DataTable dt = new DataTable();
    
                dt.TableName = "tbl_products";
                dt.Columns.Add(new DataColumn("barcode", typeof(string)));
    
                //saving databale into viewstate 
                ViewState["tbl_products"] = dt;
                //bind Gridview 
                Gv1.DataSource = dt;
                Gv1.DataBind();
            }
    
            private void AddNewRecordRowToGrid()
            {
                // check view state is not null 
                if (ViewState["tbl_products"] != null)
                {
                    //get datatable from view state 
                    DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
    
                    //add data to datatable
                    DataRow drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["barcode"] = txtBarcode.Text;
    
                    //add created Rows into dataTable 
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    //Save Data table into view state after creating each row 
                    ViewState["tbl_products"] = dtCurrentTable;
                    //Bind Gridview with latest Row 
                    Gv1.DataSource = dtCurrentTable;
                    Gv1.DataBind();
                }
            }
    
            protected void GenerateBarcode(object sender, EventArgs e)
            {
                AddNewRecordRowToGrid();
            }
    
            protected void btn_Click(object sender, EventArgs e)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["tbl_products"];
                foreach (GridViewRow row in Gv1.Rows)
                {
                    string temp1 = row.Cells[0].Text;
                    //es
                    //delete from tbl_master where temp1=temp1;
                    //pa temp1;
                    //close
    
                    using (storeEntities ctx = new storeEntities())
                    {
                        var cust = (from a in ctx.tbl_products
                                    where a.barcode == temp1
                                    select a).FirstOrDefault();
    
                        if (cust != null)
                        {
                            ctx.tbl_products.Remove(cust);
                            ctx.SaveChanges();
                            //remove existing records in ViewState
                            dtCurrentTable.Rows.Remove(dtCurrentTable.Select("barcode = '" + temp1 + "'")[0]);
                            ViewState["tbl_products"] = dtCurrentTable;
                        }
                    }
                }
                Gv1.DataSource = dtCurrentTable;
                Gv1.DataBind();
            }
    <body>
        <form id="form1" runat="server">
            <div class="container-fluid">
                <h3 style="color: black; font-size: 2.8em">Remove Purchase Barcode</h3>
                <hr />
                <div class="row">
                    <div class="col-sm-6">
                        <asp:TextBox ID="txtBarcode" runat="server" class="form-control" Width="220px"></asp:TextBox><br />
                        <asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="GenerateBarcode" class="btn btn-primary" />
                    </div>
                </div>
                <asp:Image ID="imgBarcode" runat="server" Visible="false" />
                <br />
                <br />
                <% if (Gv1.Rows.Count == 0)
                    { %>
                <div class="card border-primary mb-3" style="width: 100%">
                    <div class="card-header">Sorry, No Data</div>
                    <%--     <div class="card-body text-primary">
                        <h5 class="card-title">Sorry, No Data</h5>
                        <p class="card-text">Please add product information.</p>
                    </div>--%>
                </div>
                <% } %>
                <asp:GridView runat="server" AutoGenerateColumns="False" ID="Gv1" BackColor="#0063A4" BorderColor="#999999" HeaderStyle-ForeColor="White" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" CellSpacing="1" Width="100%">
                    <AlternatingRowStyle HorizontalAlign="Justify" Wrap="False" />
                    <Columns>
                        <asp:BoundField DataField="barcode" HeaderText="Barcode" HeaderStyle-ForeColor="White" />
                    </Columns>
                    <FooterStyle BackColor="#CCCCCC" />
                    <HeaderStyle BackColor="Transparent" Font-Bold="True" ForeColor="Black" />
                    <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
                    <RowStyle BackColor="White" />
                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                    <SortedAscendingCellStyle BackColor="#F1F1F1" />
                    <SortedAscendingHeaderStyle BackColor="#808080" />
                    <SortedDescendingCellStyle BackColor="#CAC9C9" />
                    <SortedDescendingHeaderStyle BackColor="#383838" />
                </asp:GridView>
                <asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" class="btn btn-primary" />
            </div>
        </form>
    </body>

    Result:

    It can be clearly seen that there are no two records, bbb and fff, in the database table, so they are retained.

    Please use a debugging tool to find the cause of the problem, and then try to solve it.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 17, 2020 8:27 AM