0

I have a gridview with checkbox controls as columns and with Autopostback='true' for inserting to db. Everyting works fine except when i "change pages" - Postback (?)

My checked checkboxes gets unchecked when I go back to the page.

My Page_Load have a !IsPostBack and then i bound my gridview (gwPlanning)

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

and my code behind:

protected void myCheckBox_OnCheckedChange(object sender, EventArgs e)
{

    CheckBox myCheckBox = (CheckBox)sender;
    GridViewRow row = (GridViewRow)myCheckBox.NamingContainer;

    string ThisWeekMinus2 = row.Cells[1].Text;
    bool status = myCheckBox.Checked;

    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("UPDATE [BI_Planning].[dbo].[tblPlanning] SET [This Week - 2] = @IsActive WHERE ActivityID = @ID  ", con);
        cmd.Parameters.Add("@IsActive", SqlDbType.Bit).Value = myCheckBox.Checked;
        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ThisWeekMinus2;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

    }        

}

any idea what i'm missing?

Nils
  • 516
  • 3
  • 9
  • 33
  • Whats in `BindGridViewPlanning()` do you have the set values when you read from db? Probably not loading correctly to the gridview. The checkboxes are getting made but they have no initial load values so they are always not selected. – H.Mikhaeljan Apr 13 '18 at 11:46
  • the problem for me is that the db gets updated with 'true' when the checkbox i checked but the checkbox is not checked when page is updated but the db value is still 'true' – Nils Apr 13 '18 at 11:56
  • There is already a answer given to this. Check this [link](https://stackoverflow.com/a/17792216/7324631). You can apply the 2nd solution. – H.Mikhaeljan Apr 13 '18 at 11:58
  • The 2nd solution i think you mean "Checked='<%#Convert.ToBoolean(Eval("isChecked"))%>'" the error i get there is "String was not recognized as a valid Boolean." – Nils Apr 13 '18 at 12:16
  • to make it more clear. Please set a breakpoint on `gwPlanning.DataSource = ds.Tables[0];`. Check the name of the bool value in the datasource. Specify this name in the Eval. And see if it works. Hope this helps – H.Mikhaeljan Apr 13 '18 at 12:27

1 Answers1

0

The solution was just to add:

Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%>

<asp:CheckBox ID="CheckBox1" AutoPostBack="true"  Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%> OnCheckedChanged="myCheckBox_OnCheckedChange" runat="server" Style="text-align: center" />
Nils
  • 516
  • 3
  • 9
  • 33