通过页面导航aspx.net来保持dataTable的存在

时间:2015-01-22 11:20:09

标签: asp.net

我有数据表,它是动态创建的并且绑定到网格视图,页面有一个按钮,用于在单击时将用户重定向到另一个页面。那是第1页。现在当用户在第2页上被重定向时,如果他想要回到第1页,我希望在页面加载时出现数据表。一些示例代码如何做到这一点?

第1页

protected void Page_Load(object sender, EventArgs e)
{
    dtCurrentTable = (DataTable)ViewState["Markici"];
    GridView2.DataSource = dtCurrentTable();
    GridView2.DataBind();
 }

 public void Button2_Click(object sender, EventArgs e)
 {  
      Response.Redirect("Page2.aspx");
 }
  //method for insert dataTable in database
public void Button2_Click(object sender, EventArgs e)
    { 
     dtCurrentTable = (DataTable)ViewState["Markici"];
            Session["Markici"] = dtCurrentTable;
            dtCurrentTable = (DataTable)Session["Markici"];
            GridView2.DataSource = dtCurrentTable;
            GridView2.DataBind();

            SqlCommand cmd = new SqlCommand("InsertMarkica",conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "InsertMarkica";
            foreach (DataRow dr in dtCurrentTable.Rows)
            {
                cmd.Parameters.Clear();
                //SqlCommand cmd = new SqlCommand(cmdstr, conn);
                cmd.Parameters.AddWithValue("@FirmaID", dr["FirmaID"]);
                cmd.Parameters.AddWithValue("@Godina", dr["Godina"]);
                cmd.Parameters.AddWithValue("@Kasa", dr["KasaID"]);
                cmd.Parameters.AddWithValue("@Masa", dr["Masa"]);
                cmd.Parameters.AddWithValue("@MarkicaID", dr["MarkicaID"]);
                cmd.Parameters.AddWithValue("@Datum", dr["Datum"]);
                cmd.Parameters.AddWithValue("@VrabotenID", dr["VrabotenID"]);
                cmd.Parameters.AddWithValue("@Smena", dr["Smena"]);
                cmd.Parameters.AddWithValue("@VkIznos", dr["VkIznos"]);
                cmd.Parameters.AddWithValue("@VkDanok", dr["VkDanok"]);
                cmd.ExecuteNonQuery();
                cmd.Connection = conn;
            }

第2页

public void Button2_Click(object sender, EventArgs e)
{
    Reponse.Redirect("Page1.aspx");
   //Now when is redirected on page1, it should be present data Tale,
   //needed that data Table for inserting records in database
}

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式创建会话变量

protected void Page_Load(object sender, EventArgs e)
{
    dtCurrentTable = (DataTable)ViewState["Markici"];
    Session["Markici"]=dtCurrentTable;
    GridView2.DataSource = dtCurrentTable();
    GridView2.DataBind();
}

不会在任何页面的当前会话中提供Session["Markici"]的值。您需要按照以下方式投射和使用

 dtCurrentTable = (DataTable)Session["Markici"];