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

时间:2022-11-09 03:30:47

I want to pass all the gridview value into another page I have one gridview in PatientDetails.aspx page and one button as below

我想将所有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" />

on codebehind of PatientDetails.aspx is as below

在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);
    }
}

Now on the second page name Patientstaticformatrix.aspx the code behind is as below

现在在第二页上名为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 />");
    }
}

I had debug the code in second page....the value for gvDoctorList is null as well as the selectedRow is showing error of nullreference.

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

Can you please let me where I am wrong?

你能告诉我哪里错了吗?

5 个解决方案

#1


4  

As i have seen your previous question also, So i can suggest you one thing, rather than keeping your gridview in session(which is expensive) you can use RowCommand event, and after having button here i don't think you need checkbox or chk_CheckedChanged event, you can pass the PatientID to your next page there you can write query to insert selected row data to your new table.

正如我已经看到你之前的问题,所以我可以建议你一件事,而不是保持你的gridview会话(这是昂贵的)你可以使用RowCommand事件,并在这里有按钮后我认为你不需要复选框或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");
            }
        }

On page_Load Event

在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


4  

Try using Session Variables. You can set the GridView into a Session variable that can then be retreived later so long as the same session is still active.

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

You can use the following code to set the Session Variable on your first page :

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

Session["gvDoctorList"] = gvDoctorList;

And then to retreive from the variable on your second page :

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

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

For more information on Sessions see the MSDN Session State Overview.

有关会话的详细信息,请参阅MSDN会话状态概述。

#3


1  

I have decided to add a second answer based on the correct comments from Ahmed, The session variables really shouldn't hold the amount of data of the gridview due to memory issues.

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

The following should work accordingly for what I assume you are doing :

以下应该相应地适用于我假设您正在做的事情:

Essentially when you are selecting the row to go to the next page you are trying to retrieve the data of that row onto the new page. Is this Assumption correct? If so then you have a number of options for you to use.

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

Again you could use the Session Variables to store the data of the row once extracted on the first page :

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

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);
    }
}

Essentially here you are on the first page and you get the data from the row. You then store this data in session variables and you can use the following to find the data from the next page :

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

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 />");
    }
}

You also have a second option of using Query Strings to pass the data. Although for this method I believe you will have to change the Server.Transfer("Patientstaticformatrix.aspx"); to be Response.Redirect("Patientstaticformatrix.aspx");

您还可以使用查询字符串传递数据。虽然对于这种方法我相信你将不得不改变Server.Transfer(“Patientstaticformatrix.aspx”);成为Response.Redirect(“Patientstaticformatrix.aspx”);

Below is an example on using Query Strings :

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

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);
    }
}

And to retrieve the values from the Request.QueryString object on the second page.

并从第二页上的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 />");
    }
}

Both of these solutions should meet your requirements, however they are both slightly different. The Session Variable solution is probably the preferred method as it will stop users from being able to see all of the data passed (if you need to pass confidential information) where as the Query String values will be available to anyone who can see the URL.

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

For more information on Session Variables and Query Strings see the below resources :

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

ASP.NET Session State Overview

ASP.NET会话状态概述

Request.QueryString Collection

#4


0  

@Nunners answer is ownsome, but can also try with following way:

@Nunners答案很有用,但也可以尝试以下方式:

on anothoer page's pageload event fetch grid like:

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

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

All the technique is given below:

所有技术如下:

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

Refer above doccument.

请参阅上述文件。

#5


0  

The real answer is that you should create the same gridview on another page. This is how 99% of ASP.NET sites work since that page at some point will be writing/updating/deleting data. Or just use the same page - why redirect to show the same data?

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

#1


4  

As i have seen your previous question also, So i can suggest you one thing, rather than keeping your gridview in session(which is expensive) you can use RowCommand event, and after having button here i don't think you need checkbox or chk_CheckedChanged event, you can pass the PatientID to your next page there you can write query to insert selected row data to your new table.

正如我已经看到你之前的问题,所以我可以建议你一件事,而不是保持你的gridview会话(这是昂贵的)你可以使用RowCommand事件,并在这里有按钮后我认为你不需要复选框或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");
            }
        }

On page_Load Event

在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


4  

Try using Session Variables. You can set the GridView into a Session variable that can then be retreived later so long as the same session is still active.

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

You can use the following code to set the Session Variable on your first page :

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

Session["gvDoctorList"] = gvDoctorList;

And then to retreive from the variable on your second page :

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

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

For more information on Sessions see the MSDN Session State Overview.

有关会话的详细信息,请参阅MSDN会话状态概述。

#3


1  

I have decided to add a second answer based on the correct comments from Ahmed, The session variables really shouldn't hold the amount of data of the gridview due to memory issues.

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

The following should work accordingly for what I assume you are doing :

以下应该相应地适用于我假设您正在做的事情:

Essentially when you are selecting the row to go to the next page you are trying to retrieve the data of that row onto the new page. Is this Assumption correct? If so then you have a number of options for you to use.

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

Again you could use the Session Variables to store the data of the row once extracted on the first page :

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

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);
    }
}

Essentially here you are on the first page and you get the data from the row. You then store this data in session variables and you can use the following to find the data from the next page :

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

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 />");
    }
}

You also have a second option of using Query Strings to pass the data. Although for this method I believe you will have to change the Server.Transfer("Patientstaticformatrix.aspx"); to be Response.Redirect("Patientstaticformatrix.aspx");

您还可以使用查询字符串传递数据。虽然对于这种方法我相信你将不得不改变Server.Transfer(“Patientstaticformatrix.aspx”);成为Response.Redirect(“Patientstaticformatrix.aspx”);

Below is an example on using Query Strings :

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

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);
    }
}

And to retrieve the values from the Request.QueryString object on the second page.

并从第二页上的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 />");
    }
}

Both of these solutions should meet your requirements, however they are both slightly different. The Session Variable solution is probably the preferred method as it will stop users from being able to see all of the data passed (if you need to pass confidential information) where as the Query String values will be available to anyone who can see the URL.

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

For more information on Session Variables and Query Strings see the below resources :

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

ASP.NET Session State Overview

ASP.NET会话状态概述

Request.QueryString Collection

#4


0  

@Nunners answer is ownsome, but can also try with following way:

@Nunners答案很有用,但也可以尝试以下方式:

on anothoer page's pageload event fetch grid like:

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

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

All the technique is given below:

所有技术如下:

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

Refer above doccument.

请参阅上述文件。

#5


0  

The real answer is that you should create the same gridview on another page. This is how 99% of ASP.NET sites work since that page at some point will be writing/updating/deleting data. Or just use the same page - why redirect to show the same data?

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