Search code examples
asp.netstringbuttonviewstaterowcommand

ViewState for private string with button


I have gridview with a Rowcommand event that let's me get the column ActivityID cell value and puts it in a private string called 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;
    }

This all works when the row is selected however when i press my "btUpdate" button the ActivityIDString becomes 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();
            }        
    }

I understand the issue and why it becomes NULL but I don't know exactly how to solve this issue and where to use the ViewState.

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

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

    }   
}

Solution

  • this method should be something like this

    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;
    }
    

    then retrieve it in button method

    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();
            }        
    }