在 GridView (ASP.NET) 中显示会话变量?

问题描述 投票:0回答:2

刚开始使用 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
2个回答
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();

有一篇 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"))
    };

然后您可以直接绑定到它:

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

0
投票
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"))
    };
© www.soinside.com 2019 - 2024. All rights reserved.