2010-08-18 85 views
2

剛剛從ASP.NET開始,發現很難使用GridView。我有一組Session變量,我想將它們放入GridView控件中,但我缺乏這方面的知識。該文件:在GridView(ASP.NET)中顯示會話變量?

<%@ Page Title="Warehouse" Language="C#" AutoEventWireup="true" 
    MasterPageFile="~/Site.master" 
    CodeFile="Warehouse.aspx.cs" Inherits="Warehouse" %> 

<asp:Content ID="HeaderContent" runat="server" 
    ContentPlaceHolderID="HeadContent"> 
</asp:Content> 
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 
    <h2> 
     Warehouse 
    </h2> 
    <asp:Panel ID="WarehousePanel" runat="server"> 
     <asp:GridView ID="GridView1" runat="server"> 
     </asp:GridView> 
    </asp:Panel> 
</asp:Content> 

在後面的代碼中,我想將會話變量添加到GridView1,僅用於顯示目的。稍後它將連接到數據庫,但對於練習,我想知道如何將我的會話變量添加到GridView1。該文件:

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

public partial class Warehouse : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (Session["milk"] == null) 
       Session["milk"] = "0"; 
      if (Session["apple"] == null) 
       Session["apple"] = "0"; 
      if (Session["orange"] == null) 
       Session["orange"] = "0"; 

      // on page load, add session variables ie Session["milk"].ToString(); 
      // column 1: inventory name 
      // column 2: inventory value 
      GridView1.? 
     } 
    } 

我可能會認爲這一切都是錯誤的。如果我這樣做,請糾正我到正確的道路!感謝Thanx。

+0

你還沒有真正得到任何地方,我建議你多看些書。 – leppie 2010-08-18 07:52:24

回答

4

這就像把這個在你的Page_Load簡單:

// Sample to add a value to session to ensure that something is shown 
Session.Add("SessionValue1", "Value"); 

// Actual work of binding Session to the grid 
GridView1.DataSource = Session; 
GridView1.DataBind(); 

有一個微軟Knowledge Base article是去一些方法來回答你的問題(S),因爲它提供數據的一些例子在行動和鏈接綁定進一步提供額外細節的文章。

假設你有一些代碼,如:

var warehouseItems = 
    from item in DataTableContainingWarehouseItems.AsEnumerable() 
    select 
    new 
    { 
     InventoryName = item.Field<string>("Name"), 
     InventoryValue = item.Field<int>("Value"), 
     InventoryPrice = item.Field<decimal>("Price"), 
     StockOnHandValue = Convert.ToDecimal(item.Field<int>("Value") * item.Field<decimal>("Price")) 
    }; 

你可以然後直接綁定到:

GridView1.DataSource = warehouseItems; 
GridView1.DataBind(); 
+0

Thanx!這使我走上了正確的道路...... BR – 2010-08-18 08:07:31