Ben*_*erg 2 c# asp.net gridview session-variables
刚从ASP.NET开始,发现很难使用GridView.我有一组Session变量,我想放入GridView控件,但我缺乏知识.文件:
<%@ 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>
Run Code Online (Sandbox Code Playgroud)
在后面的代码中我想将会话变量添加到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.?
}
}
Run Code Online (Sandbox Code Playgroud)
我可能会认为这一切都错了.如果我这样做,请纠正我正确的道路!Thanx听.
就像把它放在你的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();
Run Code Online (Sandbox Code Playgroud)
有一篇Microsoft 知识库文章在某种程度上回答了您的问题,因为它提供了一些数据绑定的实例和链接到更多文章,提供了更多细节.
假设您有一些代码,例如:
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"))
};
Run Code Online (Sandbox Code Playgroud)
然后你可以直接绑定到:
GridView1.DataSource = warehouseItems;
GridView1.DataBind();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7804 次 |
| 最近记录: |