将ASP.Net GridView从一个页面传递到另一个页面

时间:2013-10-09 07:54:02

标签: c# asp.net gridview

我想将所有gridview值传递到另一个页面 我在PatientDetails.aspx页面有一个gridview,下面有一个按钮

<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
    AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateSelectButton="true"
    AutoGenerateDeleteButton="true" OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />
                <asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
                <asp:Button ID="btnSelect" runat="server" Text="Select" CommandName = "Select" />
            </ItemTemplate>
        </asp:TemplateField>

        <asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
        <asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
        <asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />                                
        <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" 
    SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" OnCommand="btnformatric_Command" />

关于PatientDetails.aspx的代码隐藏如下

protected void btnformatric_Click(object sender, EventArgs e)
{
    if (gvDoctorList.SelectedRow != null)
    {
        Server.Transfer("Patientstaticformatrix.aspx");
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
    }
}

现在在第二页上名为Patientstaticformatrix.aspx,后面的代码如下

protected void Page_Load(object sender, EventArgs e)
{
    if (this.Page.PreviousPage != null)
    {
        GridView gvDoctorList = (GridView)this.Page.PreviousPage.FindControl("gvDoctorList");

        GridViewRow selectedRow = gvDoctorList.SelectedRow;
        Response.Write("PatientId: " + selectedRow.Cells[0].Text + "<br />");
        Response.Write("firstname: " + selectedRow.Cells[1].Text + "<br />");
        Response.Write("lastname: " + selectedRow.Cells[2].Text + "<br />");
    }
}

我在第二页调试了代码.... gvDoctorList的值为null,而且selectedRow显示了nullreference的错误。

你能告诉我错在哪里吗?

6 个答案:

答案 0 :(得分:4)

尝试使用会话变量。您可以将GridView设置为Session变量,只要同一会话仍处于活动状态,就可以在以后对其进行检索。

您可以使用以下代码在第一页上设置会话变量:

Session["gvDoctorList"] = gvDoctorList;

然后从第二页上的变量中搜索:

GridView gvDoctorList = (GridView)Session["gvDoctorList"];

有关会话的详细信息,请参阅MSDN Session State Overview

答案 1 :(得分:4)

正如我之前也看到过您的问题所以,我可以向您推荐一件事,而不是将您的gridview保持在会话中(这很昂贵),您可以使用RowCommand事件,并在button之后在这里,我认为您不需要复选框或chk_CheckedChanged事件,您可以将PatientID传递到下一页,您可以编写查询以将选定的行数据插入到新表中。

 <asp:TemplateField>
       <ItemTemplate>
        <asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged"  
         AutoPostBack="true" />
        <asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'> 
       </asp:Label>
      <asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# 
       Eval("PatientId") %>' CommandName = "Select" />
      </ItemTemplate>
    </asp:TemplateField>



 protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                int pID = Convert.ToInt32(e.CommandArgument);
                // either put ID in session and check 
                Session["PatientID"] = Convert.ToString(pID);
                Server.Transfer("Patientstaticformatrix.aspx");
            }
        }

在page_Load事件

 protected void Page_Load(object sender, EventArgs e)
    {
         string pID = Convert.ToString(Session["PatientID"]);
            if(!string.IsNullOrEmpty(pID))
            {
              int patientID = Convert.ToInt32(pID);
             //Call Stored procedure which will insert this record with this ID
             // to another table
            }    

    }

答案 2 :(得分:3)

我决定根据Ahmed的正确评论添加第二个答案,会话变量实际上不应该因为内存问题而保留gridview的数据量。

以下内容应该相应地符合我的假设:

基本上,当您选择要转到下一页的行时,您尝试将该行的数据检索到新页面上。这个假设是正确的吗?如果是这样,那么您可以使用多种选项。

再次,您可以使用会话变量来存储在第一页上提取的行的数据:

protected void btnformatric_Click(object sender, EventArgs e) {
    if (gvDoctorList.SelectedRow != null) {

        GridViewRow selectedRow = gvDoctorList.SelectedRow;

        Session["PatientId"] = selectedRow.Cells[0].Text;
        Session["firstname"] = selectedRow.Cells[1].Text;
        Session["lastname"] = selectedRow.Cells[2].Text;

        Server.Transfer("Patientstaticformatrix.aspx");
    } else {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
    }
}

基本上,您在第一页上,然后从行中获取数据。然后,将此数据存储在会话变量中,您可以使用以下内容从下一页中查找数据:

protected void Page_Load(object sender, EventArgs e) {
    if (this.Page.PreviousPage != null) {
        //Retrieve values from Session Variables
        Response.Write("PatientId: " + Session["PatientId"].ToString() + "<br />");
        Response.Write("firstname: " + Session["firstname"].ToString() + "<br />");
        Response.Write("lastname: " + Session["lastname"].ToString() + "<br />");
    }
}

您还可以使用查询字符串传递数据。虽然对于这种方法,我认为您必须将Server.Transfer("Patientstaticformatrix.aspx");更改为Response.Redirect("Patientstaticformatrix.aspx");

以下是使用查询字符串的示例:

protected void btnformatric_Click(object sender, EventArgs e) {
    if (gvDoctorList.SelectedRow != null) {
        GridViewRow selectedRow = gvDoctorList.SelectedRow;
        //Create URL with Query strings to redirect to new page
        Response.Redirect("Patientstaticformatrix.aspx?parentid=" + selectedRow.Cells[0].Text + "&firstname=" + selectedRow.Cells[1].Text + "&lastname=" + selectedRow.Cells[2].Text);
    } else {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
    }
}

并从第二页上的Request.QueryString对象中检索值。

protected void Page_Load(object sender, EventArgs e) {
    if (this.Page.PreviousPage != null) {
        //Retrieve values from Query Strings
        Response.Write("PatientId: " + Request.QueryString["parentid"].ToString() + "<br />");
        Response.Write("firstname: " + Request.QueryString["firstname"].ToString() + "<br />");
        Response.Write("lastname: " + Request.QueryString["lastname"].ToString() + "<br />");
    }
}

这两种解决方案都应该满足您的要求,但它们都略有不同。 Session Variable解决方案可能是首选方法,因为它会阻止用户查看传递的所有数据(如果您需要传递机密信息),因为查询字符串值可供任何可以看到的人使用URL。

有关会话变量和查询字符串的更多信息,请参阅以下资源:

ASP.NET Session State Overview

Request.QueryString Collection

答案 3 :(得分:0)

<@> @Nunners的回答是拥有的,但也可以尝试以下方式:

在anothoer页面的pageload事件获取网格上,如:

GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");

所有技术如下:

http://www.aspsnippets.com/Articles/Pass-Selected-Row-of-ASPNet-GridView-control-to-another-Page.aspx

参见上述文件。

答案 4 :(得分:0)

真正的答案是你应该在另一个页面上创建相同的gridview。这就是99%的ASP.NET站点的工作方式,因为该页面在某些时候将编写/更新/删除数据。或者只是使用相同的页面 - 为什么重定向显示相同的数据?

答案 5 :(得分:0)

我找到了解决方法:

在网格数据绑定后的源aspx中:

Session["gridtoexcel"] =  yourgrid;

目标aspx

 var grid = ((GridView)Session["gridtoexcel"]);

            gridToExcel.Columns.Clear();
            foreach (DataControlField col in grid.Columns)
                  gridToExcel.Columns.Add(col);
            
            gridToExcel.DataSource = grid.DataSource;
            gridToExcel.DataBind();

这样,我可以将精确的网格“克隆”到另一个页面。如果您需要某些CSS样式,请不要忘记将它们添加到目标页面中

PS:gridToExcel是您的目标网格

相关问题