【问题标题】:Adding a row in a gridview from a Dictionary<Key,Value>从 Dictionary<Key,Value> 在 gridview 中添加一行
【发布时间】:2012-01-22 22:52:35
【问题描述】:

我的 Page1.aspx 上有一个带有字段的 LinkBut​​ton 下面附上page1.aspx的图片。和 Page2.aspx 中的 gridview .. 当我点击 linkbutton 时,页面重定向到 Page2.aspx 并用必填字段填充 gridview..

必填字段在哪里

图片, 名称 = 黑帽, 标题 = 托皮, 价格 = 1200

Page1.aspx的代码:

 protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    Dictionary<string, string> OrderDict = new Dictionary<string, string>();
    if (e.CommandName == "orderClick")
    {
        string value = e.CommandArgument.ToString();
        string id = this.ListView1.DataKeys[e.Item.DataItemIndex].Value.ToString();
        OrderDict.Add(id, value);
        Session["Order"] = OrderDict;
        Response.Redirect("Page2.aspx");
        Response.Write(OrderDict);
    }
}

Page2.aspx的代码:

protected void Page_Load(object sender, EventArgs e)
{
    Dictionary<string, string> Dictionary = (Dictionary<string, string>)Session["Order"];
    //Regex reg = new Regex(@"\[([^\]]+)\]([^\[]+)");
    if (Dictionary != null)
    {
        GridView1.DataSource = Dictionary;
        //Dictionary = reg.Matches(Dictionary.ToString()).Cast<Match>().ToDictionary(x => x.Groups[1].Value
        //    , x => x.Groups[2].Value.Trim());
        //string slit = Dictionary.s
        this.GridView1.DataBind();
        //this.GridView1.DataSource = Dictionary;
        Response.Write(Dictionary.Values.Count);
    }
}

【问题讨论】:

  • 这里的实际问题是什么?

标签: c# asp.net dictionary


【解决方案1】:

这是我第一次看到绑定到字典的代码。您应该绑定到字典的 Keys 属性。

// Change your original line in Page_Load to this... The variable name conflicts with the class name
Dictionary<string, string> orderDictionary = (Dictionary<string, string>)Session["Order"];

// Bind like this:
GridView1.DataSource = orderDictionary.Keys;

Dictionary(Of TKey, TValue).Keys Property

您是否考虑过创建一个类来表示您在 Session 中存储的项目列表?例如:

public class SelectedOrder
{
    public string ID { get; set; }
    public string Value { get; set; }
}

// Then in your ListView ItemCommand in Page1.aspx
var orders = ((List<SelectedOrder>)Session["Order"]) ?? new List<SelectedOrder>();
orders.Add(new SelectedOrder() { ID = id, Value = value });
Session["Order"] = orders;

// And in Page2
List<SelectedOrder> orders = (List<SelectedOrder>)Session["Order"];
if (null != orders) {
    GridView1.DataSource = orders;
    GridView1.DataBind();

    // Rest of code follows...
}

我认为这将是一种更容易在您的代码中处理的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2011-01-10
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多