如何逐个将gridview聚焦的行值放入网格中

时间:2011-05-26 05:32:29

标签: c# asp.net

我有一个主细节网格。当我专注于主网格时,它将显示信息详细网格。它一次显示一个焦点一个网格,但希望保留先前数据的详细网格和第二个聚焦行数据在网格中被之前的数据所覆盖

1 个答案:

答案 0 :(得分:0)

您可以处理主网格的SelectedIndexChanged事件,并将所选项目的datakey放入单独的列表中。之后重新绑定细节网格使用所有主网格数据冷杉那些id存储在该列表中。

<asp:GridView ID="MasterGridView" runat="server" AutoGenerateColumns="false" Caption="Master"
        DataKeyNames="Id">
        <Columns>
            <asp:CommandField ShowSelectButton="true" SelectText="Select" />
            <asp:BoundField HeaderText="Id" DataField="Id" />
            <asp:BoundField HeaderText="Name" DataField="Name" />
        </Columns>
    </asp:GridView>
    <hr />
    <asp:GridView ID="DetailsGridView" runat="server" AutoGenerateColumns="false" 
        DataKeyNames="Id" Caption="Details">
        <Columns>
            <asp:CommandField ShowSelectButton="true" SelectText="Select" />
            <asp:BoundField HeaderText="Id" DataField="Id" />
            <asp:BoundField HeaderText="Name" DataField="Name" />
            <asp:BoundField HeaderText="Age" DataField="Age" />
        </Columns>
    </asp:GridView>

代码隐藏:

    private List<MyClass> MasterGridViewDataSource
    {
        get { return Session["MasterGridViewDataSource"] as List<MyClass>; }
        set { Session["MasterGridViewDataSource"] = value; }
    }

    private List<int> SelectedIDs
    {
        get { return ViewState["SelectedIDs"] as List<int>; }
        set { ViewState["SelectedIDs"] = value; }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        MasterGridView.SelectedIndexChanged += MasterGridView_OnSelectedIndexChanged;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var masterGridDataSource = GetMasterGridDataSource();
            MasterGridViewDataSource = masterGridDataSource;
            MasterGridView.DataSource = masterGridDataSource;
            MasterGridView.DataBind();

            SelectedIDs = new List<int>();
        }
    }

    private List<MyClass> GetMasterGridDataSource()
    {
        return (from item in Enumerable.Range(1, 10)
                select new MyClass { Id = item, Name = string.Format("Item #{0}", item), Age = item })
                .ToList();
    }

    void MasterGridView_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        var selectedId = (int)MasterGridView.SelectedDataKey.Value;
        if (!SelectedIDs.Contains(selectedId))
            SelectedIDs.Add(selectedId);

        DetailsGridView.DataSource = (from item in MasterGridViewDataSource
                                      join id in SelectedIDs on item.Id equals id
                                      select item);
        DetailsGridView.DataBind();
    }

    [Serializable]
    public class MyClass
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }