簡體   English   中英

綁定后如何臨時存儲數據表

[英]How to temporarily store DataTable after Binding

我有兩個GridView,其中從數據庫填充PageStart上的數據。 刷新頁面時(在“回發”上),我看不到數據表內容。 所以我想到了在每個頁面加載上再次對GridView進行數據綁定。 為了綁定數據,我需要將數據臨時存儲在某個地方。 哪一種是臨時存儲數據的最佳方法?

在我的第一個Grid中,大約有10行,而在第二個GridView中,我大約有200行。 而且我沒有使用分頁

緩存對象與會話的再次使用將取決於您是希望每個會話臨時存儲數據還是要存儲所有相同數據的所有會話。 如果您只希望為應用程序的特定會話維護相同的數據,則可以使用會話。 緩存可用於應用程序中的所有用戶會話。

要解決回發之間的數據持久性問題,您有幾種選擇。 我確實反對ViewState,但在非常特殊的情況下,您的數據量很少(這是Microsoft在WebForms中失敗的地方-它的默認行為是DemoWare)。

我建議將您的數據保留在Cache對象中,並在回發時從該對象中讀取數據。 但這確實取決於您的特定用例。 有不同的技術。

會話是存儲數據的最佳位置。 Viewstate會將所有數據帶到客戶端,這是不希望的網絡/帶寬開銷。

您的PageStart應該看起來像這樣:

public void PageStart()
{
if(Session["dt"] == null || !(Session["dt"] is datatable)){


datatable dt;
///your dt populating code
Session["dt"] = dt;
}
yourGridView.datasource = (datatable)Session["dt"];
yourGridView.databind();

} 

這就是您需要做的所有事情。
放置您的方法或函數,以此類數據填充gridview。

private void FillGrid()
{
    DataTable dt = new DataTable();
    dt = //Fill you datatable
    Gridview1.DataSource = dt;
    Gridview1.DataBind();
}

這是您必須在pageload事件上執行的操作。

protected void Page_Load(object sender, EventArgs e)  
{  
    if (!IsPostBack)  
    {  
        this.FillGrid();  
    }  
} 

這是使用ViewState的完整示例,但您可以將其更改為其他緩存方法。

在此處輸入圖片說明

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView runat="server" ID="gvProd" AutoGenerateColumns="false" OnRowDataBound="gvProd_RowDataBound" OnRowCommand="gvProd_RowCommand">
            <Columns>
                <asp:TemplateField HeaderText="Product">
                    <ItemTemplate>
                        <asp:Literal runat="server" ID="litNm"></asp:Literal>
                        <asp:DropDownList runat="server" ID="ddlQty"></asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Add To Cart">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lbnAdd" Text="Add To Cart" CommandName="AddToCart"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <hr />
        <asp:GridView runat="server" ID="gvCart" AutoGenerateColumns="false" OnRowDataBound="gvCart_RowDataBound" OnRowCommand="gvCart_RowCommand">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Literal runat="server" ID="litNm"></asp:Literal>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox runat="server" ID="txtQty"></asp:TextBox>
                        <asp:Button runat="server" ID="btnUpdate" Text="Update Qty" CommandName="UpdateCart" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        [Serializable]
        public class Product
        {
            public int PID { get; set; }
            public string Name { get; set; }

            public Product(int i) { this.PID = i; this.Name = "product " + i.ToString(); }
        }

        [Serializable]
        public class CartItem
        {
            public Product Prod { get; set; }
            public int Qty { get; set; }

            public CartItem(Product p, int q) { this.Prod = p; this.Qty = q; }
        }

        public List<CartItem> myCart = new List<CartItem>();
        public List<CartItem> MyCart
        {
            get
            {
                if (ViewState["cart"] == null)
                {
                    ViewState["cart"] = new List<CartItem>();
                }

                return ViewState["cart"] as List<CartItem>;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                BindProdGrid();
        }

        protected void BindProdGrid()
        {
            gvProd.DataSource = GetProducts();
            gvProd.DataBind();
        }

        protected List<Product> GetProducts()
        {
            var ret = new List<Product>();

            ret.Add(new Product(1));
            ret.Add(new Product(2));

            return ret;
        }

        protected void gvProd_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "AddToCart")
            {
                var row = (e.CommandSource as LinkButton).NamingContainer as GridViewRow;
                var ddl = row.FindControl("ddlQty") as DropDownList;

                var qty = Convert.ToInt32(ddl.SelectedValue);
                var pid = Convert.ToInt32(e.CommandArgument);

                AddToCart(pid, qty, increase: true);
                BindCartGrid(this.MyCart);
            }
        }

        protected void AddToCart(int pid, int qty, bool increase = false)
        {
            var cartItem = this.MyCart.Find(o => o.Prod.PID == pid);
            if (cartItem == null)
                this.MyCart.Add(new CartItem(new Product(pid), qty));
            else
                if (increase)
                    cartItem.Qty += qty;
                else
                    cartItem.Qty = qty;
        }

        protected void gvProd_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var item = e.Row.DataItem as Product;

                var litNm = e.Row.FindControl("litNm") as Literal;
                litNm.Text = item.Name;

                var ddlQty = e.Row.FindControl("ddlQty") as DropDownList;
                ddlQty.Items.Add(new ListItem("1", "1"));
                ddlQty.Items.Add(new ListItem("10", "10"));

                var lbnAdd = e.Row.FindControl("lbnAdd") as LinkButton;
                lbnAdd.CommandArgument = item.PID.ToString();
            }
        }

        protected void BindCartGrid(List<CartItem> items)
        {
            gvCart.DataSource = items;
            gvCart.DataBind();
        }

        protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var item = e.Row.DataItem as CartItem;

                var litNm = e.Row.FindControl("litNm") as Literal;
                litNm.Text = item.Prod.Name + " (pid:" + item.Prod.PID.ToString() + ")";

                var txtQty = e.Row.FindControl("txtQty") as TextBox;
                txtQty.Text = item.Qty.ToString();
                txtQty.Attributes["data-pid"] = item.Prod.PID.ToString();
            }
        }

        protected void gvCart_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "UpdateCart")
            {
                var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
                var txtQty = row.FindControl("txtQty") as TextBox;

                var qty = Convert.ToInt32(txtQty.Text);
                var pid = Convert.ToInt32(txtQty.Attributes["data-pid"]);

                AddToCart(pid, qty, increase: false);
                BindCartGrid(this.MyCart);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM