2

我有一个带有Rowcommand事件的 gridview,让我获取列ActivityID 单元格值并将其放入一个private string名为ActivityIDString的事件中。

private string ActivityIDString; // To be used in btUpdate   

    protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName == "Page") return;

        GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);

        string ActivityID = row.Cells[1].Text;
        ActivityIDString = ActivityID;
    }

当我选择“ btupdate”按钮时,ActiveIdString变为null时,这一切都起作用。

protected void btUpdate_Click(object sender, EventArgs e)
    {

            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ActivityID", ActivityIDString);
                con.Open();
                cmd.ExecuteNonQuery();
                BindGridviewActivity();
            }        
    }

我理解这个问题以及它为什么变为 NULL,但我不知道如何解决这个问题以及在哪里使用 ViewState。

protected void Page_Load(object sender, EventArgs e)
{   
    if (!IsPostBack)
    {

        ViewState["ActivityIDStringText"] = "ActivityIDString"; //  <-- SHOULD I CREATE THIS?????

    }   
}
4

2 回答 2

3

这个方法应该是这样的

protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "Page") return;
    GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);

    string ActivityID = row.Cells[1].Text;
    ViewState["ActivityIDString"] = ActivityID;
}

然后在按钮方法中检索它

protected void btUpdate_Click(object sender, EventArgs e)
{

        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        string ActivityIDString= Convert.ToString(ViewState["ActivityIDString"]);
        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("sp_tblActivityUpdate", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ActivityID", ActivityIDString);
            con.Open();
            cmd.ExecuteNonQuery();
            BindGridviewActivity();
        }        
}
于 2018-09-24T07:04:07.310 回答
0

您可以在此处使用会话。Whenever a row is selected add the ID in the session and retrieve the value of the session object in the btUpdate click event and then null the session .

在 gwActivity_RowCommand() 内部

Session["ActivityId"] += ";ActivityId";

在 btUpdate_Click() 内部

if(Session["ActivityId"]!=null){
    var ActivityIds = Session["ActivityId"].Split(';');  // For Mulitple Ids if Required
    Session["ActivityId"] = null;
}
于 2018-09-24T07:05:21.267 回答