【问题标题】:How to display data from one page to another in gridview on button click by using session on asp.net如何使用asp.net上的会话在按钮单击时在gridview中显示从一页到另一页的数据
【发布时间】:2018-04-16 17:30:26
【问题描述】:

提前谢谢。 我在将数据从主页的 gridview 传输到另一个搜索结果页面时遇到问题。页面只显示空白。没有数据显示。 我使用母版页。 我正在尝试从文本框中获取数据以获取搜索结果,例如来自文本框的源和目标。

参考下面的home.aspx.cs代码

protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=IT_APPS_SUPP;Initial Catalog=dotnet;Integrated Security=True; MultipleActiveResultSets=true");
        con.Open();
        string str1 = "Select * from busbooking where zone='" + txtSourceBus.Text + "' " + "and destination='" + txtDestBus.Text + "'";
        SqlCommand cmd1 = new SqlCommand(str1, con);
        cmd1.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(str1, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        Label1.Text = "";          
        SqlDataReader dr = cmd1.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();

            GridView1.Visible = true;
            dr.Close();
        }
        else
        {
            GridView1.Visible = true;
            Label1.Text = "Data not  found";
        }

        DataTable dt = GridView1.DataSource as DataTable;//set the datasource
        Session["GridData"] = dt;
        Response.Redirect("~/BusSearch.aspx",true);
    }

================================================ ==========

bussearch.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["GridData"] != null)
            {
                DataTable dt = (DataTable)Session["GridData"];
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }

================================================ ==================== 任何人都可以帮忙。,我的第二页只显示空白。

【问题讨论】:

    标签: c# asp.net gridview master-pages buttonclick


    【解决方案1】:

    尝试像这样传递 DataSet 而不是 DataTable

    Session["GridData"] = ds.Tables[0];
    

    所有其他代码都可以保持原样。

    【讨论】:

    • 我不会建议“所有其他代码都可以保持原样”。他没有使用准备好的语句来构造他的 sql 查询。由于 SQL 注入,这可能很危险
    • 好的,是的,我同意,但是为了将值从一页传递到另一页,现有代码可以工作并且不需要更改,但是至少在查询。
    【解决方案2】:

    你好,你可以这样使用 在 bussearch.aspx.cs 中

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["GridData"] != null)
                {
                    DataTable dt = new DataTable();
                    dt = Session["GridData"] as DataTable;
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    

    【讨论】:

    • 感谢您的宝贵回复@Vineet Dwivedi
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多