【问题标题】:Display Session variables in GridView (ASP.NET)?在 GridView (ASP.NET) 中显示会话变量?
【发布时间】:2010-08-18 07:50:47
【问题描述】:

刚开始使用 ASP.NET,发现很难使用 GridView。我有一组会话变量,我想将它们放入 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>

在后面的代码中,我想将会话变量添加到 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.?
        }
    }

我可能认为这一切都错了。如果我这样做,请纠正我正确的道路!感谢收听。

【问题讨论】:

  • 你还没有真正得到什么,我建议你多读书。

标签: c# asp.net gridview session-variables


【解决方案1】:

就像把它放在你的 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();

有一个 Microsoft Knowledge Base article 可以在某种程度上回答您的问题,因为它提供了一些数据绑定的实际示例以及指向提供更多详细信息的更多文章的链接。

假设您有一些代码,例如:

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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 2012-05-03
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多