Delete row from Session using GridView and display in another page using C# and VB.Net in ASP.Net

Last Reply one month ago By pandeyism

Posted one month ago

my gridview delete link button is not working.

this my code

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="container">
        <div class="content">
            <div class="row">
                <div class="auto-style2" style="margin-left: 10%; height: 100%">
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                    <asp:GridView runat="server" AutoGenerateColumns="false" ID="products_gw" CellPadding="5"
                        Class="text-center " ForeColor="Black" BackColor="#CCCCCC" BorderColor="#999999"
                        BorderStyle="Solid" BorderWidth="3px" CellSpacing="5" Height="307px" Width="836px"
                        CssClass="auto-style4" OnSelectedIndexChanged="products_gw_SelectedIndexChanged">
                        <Columns>
                            <asp:ImageField DataImageUrlField="img" />
                            <asp:TemplateField HeaderText="ProductID">
                                <ItemTemplate>
                                    <asp:Label ID="lblProductID" runat="server" Text='<%#Eval("id") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="ProductName">
                                <ItemTemplate>
                                    <asp:Label ID="lblProductName" runat="server" Text='<%#Eval("name") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Price">
                                <ItemTemplate>
                                    <asp:Label ID="lblPrice" runat="server" Text='<%#Eval("price") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Quantity">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtQty" runat="server" onkeyup="CalculateTotals();"></asp:TextBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Total">
                                <ItemTemplate>
                                    <asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Delete">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkDelete" runat="server">Delete</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <FooterStyle BackColor="#CCCCCC"></FooterStyle>
                        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White"></HeaderStyle>
                        <PagerStyle HorizontalAlign="Left" BackColor="#CCCCCC" ForeColor="Black"></PagerStyle>
                        <RowStyle BackColor="White"></RowStyle>
                        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White"></SelectedRowStyle>
                        <SortedAscendingCellStyle BackColor="#F1F1F1"></SortedAscendingCellStyle>
                        <SortedAscendingHeaderStyle BackColor="#808080"></SortedAscendingHeaderStyle>
                        <SortedDescendingCellStyle BackColor="#CAC9C9"></SortedDescendingCellStyle>
                        <SortedDescendingHeaderStyle BackColor="#383838"></SortedDescendingHeaderStyle>
                    </asp:GridView>
                    <asp:Label ID="Cart" runat="server" Font-Size="X-Large" Text="Grand Total:">
                        <asp:Label ID="lblSumTotal" runat="server"></asp:Label></asp:Label>
                </div>
            </div>
            <br />
            <div class="panel-footer ">
                <div style="margin-left: 45%;" class="">
                    <a href="checkout.aspx" class="btn btn-success" style="width: 150px; height: 35px;">
                        Proceed To Checkout</a><br />
                </div>
            </div>
            <br />
        </div>
    </div>
</asp:Content>

 

protected void Page_Load(object sender, EventArgs e)
{
    load_data();
}
void load_data()
{
    if (Session["cart"] != null)
    {
        List<Products> prods = Session["cart"] as List<Products>;
        products_gw.DataSource = prods;
        products_gw.DataBind();
    }
}

protected void products_gw_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label li = products_gw.Rows[e.RowIndex].FindControl("") as Label;
    using (SqlConnection sqlConn = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=shoppingcart"))
    {
        using (SqlCommand sqlCmd = new SqlCommand())
        {
            if (sqlConn.State == ConnectionState.Closed)
                sqlConn.Open();
            sqlCmd.Connection = sqlConn;
            sqlCmd.CommandText = "Delete from [product] where id=@Id";
            sqlCmd.Parameters.AddWithValue("@Id", li.Text);
            sqlCmd.Connection = sqlConn;
            sqlCmd.ExecuteNonQuery();
            // sqlConn.Close();
        }
    }
    load_data();
} 

 

 

Posted one month ago Modified on 28 days ago

Hi Sadia.net,

Refer below sample code.

HTML

CS.aspx

<div id="body">
    <div class="container">
        <div class="last-products">
            <h2>
                Last added products</h2>
            <section class="products">
            <%
                if (product_list.Count > 0)
                {
                    foreach (var product in product_list)
                    { %>
                <article>
                    <img src="<%=product.ImagePath%>" alt="" height="80px" width="80px"/>
                        <h3><a href="single.htm"><%=product.Name%></a></h3>
                        <div class="price">
                            <h5 class="item_price"><%=product.Price%></h5>
                            <a href="front.aspx?pro_id=<%=product.Id%>&action=add" class="item_add">Add To Cart</a>
                            <div class="clearfix"> </div>
                    </div>
                </article>
                
                <%}
                }
                else
                {
                %>
            <h2>No Product Available</h2>
            <%    }
            %>
            </section>
        </div>
    </div>
</div>

front.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function CalculateTotals() {
            var gv = document.getElementById("<%= products_gw.ClientID %>");
            var rows = gv.getElementsByTagName("tr");
            var grandTotal = 0;
            for (var i = 0; i < rows.length; i++) {
                var tds = rows[i].getElementsByTagName("td");
                if (rows[i].getElementsByTagName("td").length > 0) {
                    var price = rows[i].getElementsByTagName("span")[2].innerHTML;
                    var quantity = rows[i].getElementsByTagName("input")[0].value;
                    var total = parseFloat(price) * parseFloat(quantity);
                    rows[i].getElementsByTagName("span")[3].innerHTML = isNaN(total) ? 0 : total;
                    grandTotal += isNaN(total) ? 0 : total;
                }
            }
            document.getElementById("<%= lblSumTotal.ClientID %>").innerHTML = grandTotal;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <html xmlns="http://www.w3.org/1999/xhtml">
        <asp:GridView runat="server" AutoGenerateColumns="false" ID="products_gw">
            <Columns>
                <asp:TemplateField HeaderText="ProductID">
                    <ItemTemplate>
                        <asp:Label ID="lblProductID" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ProductName">
                    <ItemTemplate>
                        <asp:Label ID="lblProductName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Price">
                    <ItemTemplate>
                        <asp:Label ID="lblPrice" runat="server" Text='<%#Eval("Price") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Quantity">
                    <ItemTemplate>
                        <asp:TextBox ID="txtQty" runat="server" onkeyup="CalculateTotals();"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total">
                    <ItemTemplate>
                        <asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkDelete" runat="server" OnClick="Delete">Delete</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Label ID="Cart" runat="server" Font-Size="X-Large" Text="Grand Total:">
            <asp:Label ID="lblSumTotal" runat="server"></asp:Label></asp:Label>
    </div>
    <asp:LinkButton ID="LinkButton1" Text="Back" runat="server" PostBackUrl="~/CS.aspx" />
    </form>
</body>
</html>

Namespaces

C#

using System.Data;

Code

C#

CS.aspx.cs

public List<Products> product_list = new List<Products>();
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["product"] == null)
        {
            product_list.Add(new Products(1, "Desert", 1200, "Files/Desert.jpg"));
            product_list.Add(new Products(2, "Jellyfish", 2000, "Files/Jellyfish.jpg"));
            product_list.Add(new Products(3, "Penguins", 5000, "Files/Penguins.jpg"));
            Session["product"] = product_list;  
        }
        else
        {
            product_list = Session["product"] as List<Products>;
        }
    }
}

front.aspx.cs

List<Products> product_list;
static List<Products> cart_list = new List<Products>();
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        product_list = Session["product"] as List<Products>;
        if (Request.QueryString.AllKeys.Contains("pro_id") && Request.QueryString.AllKeys.Contains("action"))
        {
            string pro_id = Request.QueryString["pro_id"];
            add_to_cart(pro_id);
        }
    }
}

void add_to_cart(string product_id)
{
    var product = product_list.Where(x => x.Id == Convert.ToInt16(product_id));
    foreach (var data in product)
    {
        cart_list.Add(data);
    }
    products_gw.DataSource = cart_list;
    products_gw.DataBind();
    Session["cart"] = cart_list;
    Session["product"] = product_list;
}

protected void Delete(object sender, EventArgs e)
{
    product_list = Session["product"] as List<Products>;
    cart_list = Session["cart"] as List<Products>;
    LinkButton lnkButton = (sender) as LinkButton;
    GridViewRow row = (GridViewRow)lnkButton.NamingContainer;
    cart_list.RemoveAt(row.RowIndex);
    product_list.RemoveAt(row.RowIndex);
    products_gw.DataSource = cart_list;
    products_gw.DataBind();
    Session["product"] = product_list;
}

Screenshot