使用嵌套网格视图中选定行的值来填充另一个网格视图

本文关键字:视图 网格 另一个 填充 嵌套 | 更新日期: 2023-09-27 17:59:07

有人知道如何克服这个问题吗?非常感谢任何帮助

我用这篇令人印象深刻的文章创建了一个嵌套的网格视图——嵌套的网格图和文章中一样工作得很好。现在我想在页面中添加一个单独的第三个网格视图(OuterGridView),但不要嵌套在gvParent或gvChild中。当我从gvChild中选择一行时,我想将所选行的OrderID和EmployeeId传递给一个自定义方法(BindOuterGridView),以查询DB并在OuterGridView中显示结果。

到目前为止,我还无法填充OuterGridView

这是我的代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.Configuration;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
string _connectionString;
DataTable customersTable = null;
DataTable orderTable = null;
DataTable orderDetailTable = null;
protected void Page_Load(object sender, EventArgs e)
{
    gvParent.DataSource = GetParentTableData();       
    gvParent.DataBind();
    if (!Page.IsPostBack)
    {
        GridViewChildPageIndex();          
    }     
}
private string GetConnectionString()
{
    _connectionString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
    return _connectionString;
}
// gets data for the parent Gridview i.e.( gvParent)
private DataTable GetParentTableData()
{
    customersTable = new DataTable("Customers");
    string constr = GetConnectionString();
    string query = "SELECT top 10 [CustomerID],[CompanyName],[ContactName],[ContactTitle],[Phone] FROM [Northwind].[dbo].[Customers]";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(query, con);
    using (con)
    {
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        customersTable.Load(reader);
    }
    return customersTable;
}
// gets data for the child Gridview i.e.( gvChile)
private DataTable GetChildTableData(string custID)
{
    orderTable = new DataTable("Orders");
    string constr = GetConnectionString();
    string query = "select OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate from dbo.Orders where CustomerID= '" + custID + "'";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(query, con);
    using (con)
    {
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        orderTable.Load(reader);
    }
    return orderTable;
}
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {

        Image img = (Image)e.Row.Cells[0].FindControl("img1");
        Literal ltrl = (Literal)e.Row.FindControl("lit1");
        ltrl.Text = ltrl.Text.Replace("trCollapseGrid", "trCollapseGrid" + e.Row.RowIndex.ToString());
        string str = "trCollapseGrid" + e.Row.RowIndex.ToString();
        e.Row.Cells[0].Attributes.Add("OnClick", "OpenTable('" + str + "','" + img.ClientID + "')");
        e.Row.Cells[0].RowSpan = 1;
        System.Web.UI.WebControls.GridView gvChild = (System.Web.UI.WebControls.GridView)e.Row.FindControl("gvChild");
        if (Session["ChildPageIndex"] != null)
        {
            DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
            gvChild.PageIndex = Convert.ToInt16(dtPageIndex.Rows[e.Row.RowIndex][0]);
        }
        BindChildGrdView(gvParent.DataKeys[e.Row.RowIndex].Value.ToString(), gvChild);
    }
}
protected void gvChild_PageIndexChanging(object sender, GridViewPageEventArgs e)
{        
    System.Web.UI.WebControls.GridView gvwChild = ((System.Web.UI.WebControls.GridView)sender);
    GridViewRow gvRowParent = ((System.Web.UI.WebControls.GridView)sender).Parent.Parent as GridViewRow;
    gvwChild.PageIndex = e.NewPageIndex;
    if (Session["ChildPageIndex"] != null)
    {
        DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
        dtPageIndex.Rows[gvRowParent.RowIndex][0] = e.NewPageIndex;
    }
    BindChildGrdView(gvParent.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "document.getElementById('" + hidRowId.Value + "').style.display = '';", true);
    }
}
//Dynamically create bing gvChil
private void BindChildGrdView(string custId, System.Web.UI.WebControls.GridView gvChild)
{
    DataTable dtChildTable = GetChildTableData(custId);
    DataTable dtCloneChildTable = dtChildTable.Clone();
    DataRow[] gvChildRows = dtChildTable.Select();
    foreach (DataRow gvChildRow in gvChildRows)
    {
        dtCloneChildTable.ImportRow(gvChildRow);
    }
    gvChild.DataSource = dtCloneChildTable;
    gvChild.AllowPaging = true;
    gvChild.PageSize = 15;
    gvChild.DataBind();      
}
private void GridViewChildPageIndex()
{
    DataTable dtPageIndex = new DataTable();
    dtPageIndex.Columns.Add("PageIndex", typeof(int));
    for (int i = 0; i < gvParent.Rows.Count; i++)
    {
        dtPageIndex.Rows.Add("0");
    }
    Session["ChildPageIndex"] = dtPageIndex;
}
// gets data for the outer Gridview i.e.( OuterGridView)
private DataTable BindOuterGridView(string orderId, string EmployeeId)
{
    orderDetailTable = new DataTable("OrderDetails");
    string constr = GetConnectionString();
    string query = "SELECT [Order Details].OrderID, [Order Details].UnitPrice, [Order   Details].Quantity,Employees.FirstName +' '+ Employees.LastName as EmlpoyeeName, Orders.EmployeeID FROM Northwind.dbo.Orders INNER JOIN [Order Details] ON [Order Details].OrderID=Orders.OrderID INNER JOIN Employees ON Employees.EmployeeID=Orders.EmployeeID WHERE dbo.Orders.OrderID ='"+orderId+"'"+" AND dbo.Orders.EmployeeID='"+EmployeeId +"'";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(query, con);
    using (con)
    {
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        orderDetailTable.Load(reader);
    }       
    return orderDetailTable;
}
//when I select a row from gvChild  I grab the OrderID and EmployeeId
//and passed to BindOuterGridView method to populate OuterGridView 
protected void gvChild_RowCommand(object sender,   System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "select") {
    GridView grd = (GridView)sender;
    LinkButton lb = (LinkButton)e.CommandSource;
    GridViewRow gvRow = (GridViewRow)lb.BindingContainer;         
    string orderID =grd.DataKeys[gvRow.RowIndex].Values[0].ToString();
    string employeeID = grd.DataKeys[gvRow.RowIndex].Values[1].ToString();
    OuterGridView.DataSource = BindOuterGridView(orderID, employeeID);
    OuterGridView.DataBind();
}
}
}    

html脚本

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
 <form id="form1" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
 </asp:ScriptManager>
 <script language="javascript" type="text/javascript">
  function OpenTable(trRow, imgId) {
        object = document.getElementById(trRow);
        var rowId = document.getElementById('<%=hidRowId.ClientID %>').value;
        var imageId = document.getElementById('<%=hidImgId.ClientID %>').value;
        if (rowId != '') {
            if (document.getElementById('<%=hidImgId.ClientID %>').value != imgId) {
                document.getElementById(rowId).style.display = "none";
                document.getElementById(imageId).src = "img/Collapse.gif";
            }
        }
        document.getElementById('<%=hidImgId.ClientID %>').value = imgId;
        document.getElementById('<%=hidRowId.ClientID %>').value = trRow;
        if (object.style.display == "none") {
            object.style.display = "";
            document.getElementById(imgId).src = "img/Expand.gif";
        }
        else {
            object.style.display = "none";
            document.getElementById(imgId).src = "img/Collapse.gif";
        }
    }
</script>
<div style="height: 20px; color: red;">
    <asp:UpdateProgress runat="server" ID="PageUpdateProgress">
        <ProgressTemplate>
            <img src="img/processing.gif" alt="Processing" />
            Processing please wait......
        </ProgressTemplate>
    </asp:UpdateProgress>
</div>
<asp:UpdatePanel runat="server" ID="updTest">
    <ContentTemplate>
        <asp:GridView ID="gvParent" runat="server" DataKeyNames="CustomerID" AutoGenerateColumns="False"
            OnRowDataBound="gvParent_RowDataBound" CellPadding="4" ForeColor="#333333" ShowHeader="True">
            <Columns>
                <asp:TemplateField ItemStyle-Width="20px">
                    <ItemTemplate>
                        <asp:Image runat="server" ID="img1" ImageUrl="~/img/Collapse.GIF" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Customer ID" DataField="CustomerID">
                </asp:BoundField>
                <asp:BoundField HeaderText=" Company Name" DataField="CompanyName">
                </asp:BoundField>
                <asp:BoundField HeaderText="Contact Name" DataField="ContactName">
                </asp:BoundField>
                <asp:TemplateField HeaderText="Contact Title">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpName" runat="server" Text='<%# Eval("ContactTitle")%>'></asp:Label>
                        <asp:Literal runat="server" ID="lit1" Text="</td><tr id='trCollapseGrid' style='display:none' ><td colspan='5'>" />
                        <asp:GridView ID="gvChild" DataKeyNames="OrderID,EmployeeID"  OnPageIndexChanging="gvChild_PageIndexChanging"  OnRowCommand="gvChild_RowCommand"  AutoGenerateColumns="False"
                            runat="server" EnableViewState="False" ForeColor="#333333" AllowPaging="True">
                            <RowStyle BackColor="#EFF3FB" />
                            <AlternatingRowStyle BackColor="White" />
                            <Columns>
                             <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:LinkButton ID="Select" CommandArgument='<%# Eval("OrderID") %>' CommandName="select" runat="server">Select</asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField HeaderText="Order ID" DataField="OrderID" />
                                <asp:BoundField HeaderText="Customer ID" DataField="CustomerID" />
                                <asp:BoundField HeaderText="Employee ID" DataField="EmployeeID" />
                                <asp:BoundField HeaderText="Order Date" DataField="OrderDate" DataFormatString="{0:d}" />
                                <asp:BoundField HeaderText="Require dDate" DataField="RequiredDate" DataFormatString="{0:d}" />
                            </Columns>
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        </asp:GridView>
                        <asp:Literal runat="server" ID="lit2" Text="</td></tr>" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#EFF3FB" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:HiddenField ID="hidRowId" runat="server" />
<asp:HiddenField ID="hidImgId" runat="server" />
<asp:GridView ID="OuterGridView" runat="server">
</asp:GridView>
</form>

非常感谢。

使用嵌套网格视图中选定行的值来填充另一个网格视图

这不是一个很好的解决方案,但是,如果你急于找到解决方案,你可以这样做来快速完成任务。

在子网格视图的行数据绑定事件上,添加一个onclick事件,该事件使用特殊的查询字符串将用户重定向到同一页面,比如skill&empid。在页面加载时检查它们是否存在。如果是,请调用BindOuterGridView方法。

protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            object objTemp = gvChild.DataKeys[e.Row.RowIndex].Value as object;
            if (objTemp != null)
            {
                string id = objTemp.ToString();
                e.Row.Attributes["onmouseover"] = "this.style.color='DarkGrey';this.style.cursor='hand';";
                e.Row.Attributes["onmouseout"] = "this.style.color='Black';";
                e.Row.Attributes["onclick"] = "window.location.href = 'yourpage.aspx?Id=" + id + "'";
            }
        }
    }