Display Session variables in GridView (ASP.NET)?
Just starting with ASP.NET and find it difficult to use the GridView. I have a set of Session variables which I want to put into a GridView control, but I lack the knowledge. The file:
<%@ 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>
&l开发者_如何学编程t;/asp:Content>
In the code behind I want to add the session variables to the GridView1, just for display purposes. Later on it will be connected to a database, but for practice, I want to know how I can add my session variables to the GridView1. The file:
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.?
}
}
I might be thinking this all wrong. If I do, please correct me to the right path! Thanx for listening.
It's as simple as putting this in your 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();
There's a Microsoft Knowledge Base article that goes some way to answering your question(s) as it provides some examples of Data Binding in action and links to further articles giving additional detail.
Assuming you had some code such as:
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"))
};
You could then bind directly to that:
GridView1.DataSource = warehouseItems;
GridView1.DataBind();
精彩评论