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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19266128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:32:36  来源:igfitidea点击:

Pass ASP.Net GridView from one page to another page

c#asp.netgridview

提问by Pratik

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?

你能告诉我我错在哪里吗?

采纳答案by Suraj Singh

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 RowCommandevent, and after having buttonhere i don't think you need checkbox or chk_CheckedChangedevent, you can pass the PatientIDto your next page there you can write query to insert selected row data to your new table.

正如我也看到您之前的问题,所以我可以建议您做一件事,而不是将您的 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");
            }
        }

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
            }    

    }

回答by Nunners

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 会话状态概述

回答by C Sharper

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

@Nunners 的回答是自己的,但也可以尝试以下方式:

on anothoer page's pageload event fetch grid like:

在另一个页面的 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

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

Refer above doccument.

参考上面的文档。

回答by Ahmed ilyas

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 站点的工作方式,因为该页面在某些时候将写入/更新/删除数据。或者只是使用相同的页面 - 为什么重定向以显示相同的数据?

回答by Nunners

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.QueryStringobject 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 Variablesolution 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.

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

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

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

ASP.NET Session State Overview

ASP.NET 会话状态概述

Request.QueryString Collection

Request.QueryString 集合