sagar Bhosale

sagar Bhosale

  • NA
  • 179
  • 175.7k

How delete data from gridview without using database table?I am retrive data using dictionary & fetch to gridview?

Mar 30 2011 10:09 AM
how delete data from gridview  without using database table?I am retrive data using dictionary & fetch to gridview?
Hi frends i want to delete recorde from gridview but that data is store in database i am  using session .
This is an shopping cart project once i select product that product stored in dictionary using session i passed that data to mycart page & bound session with gridview .

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) {
try {
//new ProductContext(ConfigurationManager.ConnectionStrings["ShoppingDBConnectionString"].ConnectionString).
//        DeleteProduct(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["ProductId"].ToString()));


new ProductContext(ConfigurationManager.ConnectionStrings["ShoppingDBConnectionString"].ConnectionString).
DeleteProduct(int.Parse(GridView1.DataKeys[e.RowIndex].Values["ProductId"].ToString()));
GridView1.EditIndex = -1;
GridView1.DataBind();

} catch (Exception ex) {
       throw ex;
}
This is give me error please suggesr how to resolve my problem my source code is given below

Productdetail.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/ShoppingApp.Master" AutoEventWireup="true" CodeBehind="ProductDetails.aspx.cs" Inherits="ShoppingCart.ProductDetails" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <table class="style1">
        <tr>
            <td>
                <asp:DataList ID="DataList1" runat="server" CellPadding="4" 
                    DataKeyField="ProductId" DataSourceID="SqlDataSource1" ForeColor="#333333">
                    <AlternatingItemStyle BackColor="White" />
                    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                    <ItemStyle BackColor="#E3EAEB" />
                    <ItemTemplate>
                        ProductId:
                        <asp:Label ID="ProductIdLabel" runat="server" Text='<%# Eval("ProductId") %>' />
                        <br />
                        CatalogId:
                        <asp:Label ID="CatalogIdLabel" runat="server" Text='<%# Eval("CatalogId") %>' />
                        <br />
                        ProductName:
                        <asp:Label ID="ProductNameLabel" runat="server" 
                            Text='<%# Eval("ProductName") %>' />
                        <br />
                        UnitPrice:
                        <asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />
                        <br />
                        Discription:
                        <asp:Label ID="DiscriptionLabel" runat="server" 
                            Text='<%# Eval("Discription") %>' />
                        <br />
                        RealeseDate:
                        <asp:Label ID="RealeseDateLabel" runat="server" 
                            Text='<%# Eval("RealeseDate") %>' />
                        <br />
                        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrl", "{0}/images/") %>' /><br />
                        ImageUrl:
                        <asp:Label ID="ImageUrlLabel" runat="server" Text='<%# Eval("ImageUrl") %>' />
                        <br />
<br />
                    </ItemTemplate>
                    <SelectedItemStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                </asp:DataList>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:ShoppingDBConnectionString %>" 
                    SelectCommand="SELECT [ProductId], [CatalogId], [ProductName], [UnitPrice], [Discription], [RealeseDate], [ImageUrl] FROM [Product] WHERE ([ProductId]=@ProductId)">
                    <SelectParameters>
                    <asp:QueryStringParameter Name="ProductId" 
                              QueryStringField="ProductId" 
                              Type="Decimal" />
                   </SelectParameters>
                    </asp:SqlDataSource>
                     
                <br />
                <asp:Button ID="btnAdd" runat="server" Text="Add To Cart" 
                    onclick="btnAdd_Click"/>   
                
                &nbsp;&nbsp;&nbsp;   
                
                &nbsp;<asp:Label ID="Label1" runat="server" Text="Quantity"></asp:Label>
                &nbsp;&nbsp;<asp:TextBox ID="txtquantity" runat="server"></asp:TextBox>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Home.aspx">Return to Home Page</asp:HyperLink>
</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

productdetailaxpx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShoppingCart.SQL;
using System.Configuration;
using System.Data;
using System.Collections;

namespace ShoppingCart {
        public partial class ProductDetails : System.Web.UI.Page {
    
protected void Page_Load(object sender, EventArgs e) {
}


protected void btnAdd_Click(object sender, EventArgs e) {
try {
//Using Dictionary

if (Session["MyCartItems"] == null) {
//no items exist in the cart
//hence we need to create the array list in the session
Dictionary<int, int> cart = new Dictionary<int, int>();

cart.Add(int.Parse(Request.QueryString["ProductId"].ToString()),
int.Parse(txtquantity.Text));

Session["MyCartItems"] = cart;

} else {
//some items exist already in the session
//hence append items to it

Dictionary<int, int> cart = (Dictionary<int, int>)Session["MyCartItems"];

if(cart.ContainsKey(int.Parse(Request.QueryString["ProductId"].ToString()))){
cart[int.Parse(Request.QueryString["ProductId"].ToString())] = int.Parse(txtquantity.Text.Trim());
}else{
cart.Add(int.Parse(Request.QueryString["ProductId"].ToString()),
int.Parse(txtquantity.Text));
}

Session["MyCartItems"] = cart;
}

Response.Redirect("MyCart.aspx");
} catch (Exception ex) {
throw ex;
}
}

}




}
        

                        

mycart.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/ShoppingApp.Master" AutoEventWireup="true" CodeBehind="MyCart.aspx.cs" Inherits="ShoppingCart.MyCart" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
         <asp:GridView ID="GridView1" runat="server" BackColor="Maroon" Datakey="ProductId"
        BorderColor="#660033" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
        CellSpacing="2" Width="439px" 
        ForeColor="White" ShowFooter="true"  
       onrowdatabound="GridView1_RowDataBound"> 
       </asp:GridView>

   <asp:HiddenField ID="hdnGrandTotal" Value="0" runat="server" />

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:ShoppingDBConnectionString %>"
      SelectCommand="SELECT [ProductId],[ProductName],[UnitPrice],[Discription] FROM [Product] WHERE ([ProductId]=@ProductId)"> 
      </asp:SqlDataSource>
    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Home.aspx">Back To Home</asp:HyperLink>
&nbsp;</div>
</asp:Content>

 

mycartaspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShoppingCart.SQL;
using System.Configuration;
using System.Data;
using System.Collections;

namespace ShoppingCart {
public partial class MyCart : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
Bind();
}
public void Bind() {

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ProductId", typeof(int)));
dt.Columns.Add(new DataColumn("Quantity", typeof(int)));
dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
dt.Columns.Add(new DataColumn("UnitPrice", typeof(int)));
dt.Columns.Add(new DataColumn("Discription", typeof(string)));
dt.Columns.Add(new DataColumn("Total",typeof(int)));
 
if (Session["MyCartItems"] != null) {
Dictionary<int, int> cart = (Dictionary<int, int>)Session["MyCartItems"];
foreach (KeyValuePair<int, int> kvp in cart) {
 //kvp.Key
//kvp.Value

DataRow dr = dt.NewRow();
//int ProductId = kvp.Key;
//int Quantity = kvp.Value;


dr = new ProductContext(ConfigurationManager.ConnectionStrings["ShoppingDBConnectionString"].ToString()).
GetProductSummaryByProductId(kvp.Key,kvp.Value,dr);
                                dt.Rows.Add(dr);    
       }

              } else {
         //show an empty cart
                   }
     GridView1.DataSource =dt;
     GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
decimal GrandTotal=0;

 if (e.Row.RowType == DataControlRowType.DataRow){

   GrandTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total"));
   
 }
 if (e.Row.RowType == DataControlRowType.DataRow) {


 decimal currentTotal = decimal.Parse(hdnGrandTotal.Value);

 currentTotal += Convert.ToDecimal(e.Row.Cells[5].Text);

 hdnGrandTotal.Value=currentTotal.ToString();

 } else if (e.Row.RowType == DataControlRowType.Footer) {

 e.Row.Cells[2].Text = "Total:";

 e.Row.Cells[5].Text = hdnGrandTotal.Value.ToString();

 e.Row.Font.Bold = true;



}



 }
}
}

Thanks Lots..................
 

Attachment: finishshopping.rar

Answers (1)