【问题标题】:Pass ASP.Net GridView from one page to another page将 ASP.Net GridView 从一个页面传递到另一个页面
【发布时间】:2013-10-09 07:54:01
【问题描述】:

我想将所有 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);
    }
}

现在在第二页名称Patientsstaticformatrix.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 错误。

你能告诉我哪里错了吗?

【问题讨论】:

  • 你为什么要转移控制权 - 一个更简单的选择是访问绑定到网格的数据。
  • 我只希望将患者 ID 值放入另一个页面中......并希望在第二页中插入所选的患者 ID 和患者图像

标签: c# asp.net gridview


【解决方案1】:

我也看到了你之前的问题,所以我可以建议你一件事,而不是让你的 gridview 保持在会话中(这很昂贵),你可以使用RowCommand 事件,在拥有button 之后我不' t 认为您需要复选框或 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 事件

 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
            }    

    }

【讨论】:

  • 我尝试使用你的代码,它给我在线错误:int pID = Convert.ToInt32(e.CommandArgument);输入字符串的格式不正确.....该怎么办?
  • PatientId 的数据类型是什么?
  • patientid 是 int 以及 sql server 中的自动增量
  • PatientID 是唯一的吗?这个错误意味着PatientID 不能转换为 Int 类型。检查更新的答案,但只有在 PatientId 是唯一的或者您有任何主键时才使用它?
  • 您是否在您的网格视图中设置CommandArgument&lt;asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='&lt;%# Eval("PatientId") %&gt;' CommandName = "Select" /&gt;
【解决方案2】:

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

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

Session["gvDoctorList"] = gvDoctorList;

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

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

有关会话的更多信息,请参阅MSDN Session State Overview

【讨论】:

  • 我应该在复选框更改事件中还是在其他地方设置会话?
  • 您可以根据需要设置会话变量,但在您需要之前我不会设置它。像您的btnformatric_Click 中的以下内容:Session["gvDoctorList"] = gvDoctorList; Server.Transfer("Patientstaticformatrix.aspx");。这样你就不会使用内存空间,直到你需要它。
  • 我无法在会话中直接获取gridview控件gvDoctorList....这意味着我需要先设置gridview的循环,然后在里面我需要设置会话值...你怎么看?
  • 投反对票。不好的做法。就内存消耗和性能而言,对象太大而无法在会话中保存。你不应该做这样的事情(即使它有效)。你会受到很大的打击。
  • @Ahmedilyas 请在下面查看我的新扩展答案。我想我已经解决了使用会话变量的任何问题,就像我对这个答案一样。
【解决方案3】:

我决定根据来自 Ahmed 的正确 cmets 添加第二个答案,由于内存问题,会话变量确实不应该保存 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

【讨论】:

    【解决方案4】:

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

    在另一个页面的页面加载事件获取网格上,例如:

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

    所有技术如下:

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

    参考以上文档。

    【讨论】:

    • 我已经参考了你建议的链接......但在我的情况下,GridView1 的名称为 gvDoctorList......所以我已经替换它......仍然只有空引用即将到来....
    • @Pratik 看到这个rajudasa.blogspot.in/2011/08/…
    • 问题是,如果页面被移动到母版页或用户控件中怎么办?这行不通。
    • 是的,你是对的,我在母版页中有两个页面......所以我正在尝试你的 rowcommand 解决方案......希望它能正常工作
    【解决方案5】:

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

    【讨论】:

    • 我想从 gridview 中获取选择值并将选择的 patientid 插入到 sql 表中......但是在另一个页面中......bec。我想插入患者的图像,当然还有患者ID
    • 那么为什么不在同一页面上这样做呢? :)
    • 我在其他页面配置了摄像头,所以在同一页面上是不可能的
    • 我明白了。那很简单。基本上在这个有网格的页面上,让他们输入/更新详细信息,然后调用数据库,它会在成功时返回一个 ID,获取该记录 ID 并将其传递到下一页进行相机拍摄确认后,使用带有 recordID 的图像更新表。
    【解决方案6】:

    我找到了一些解决方案:

    在网格数据绑定后的 Source 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 是您的目标网格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 2021-01-14
      • 2016-01-24
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多