I have a pretty standard GridView. This includes a TemplateField with a checkbox. I set the checkboxes to checked/unchecked based on values in a database.
The checkboxes have a CheckedChanged event. After the page has loaded the first time I click a checkbox that is checked. The CheckedChanged event fires, but the CheckBox always has Checked = true. Any subsequent clicks on checkboxes, and the information in the event is correct.
What is causing this?
.aspx
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="MyGV" runat="server" DataKeyNames="Id" OnRowCreated="MyGV_RowCreated" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="My checkboxes">
<ItemTemplate>
<asp:CheckBox ID="MyCheckBox" runat="server" OnCheckedChanged="MyCheckBox_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
MyGV.DataSource = myfetcheddata;
MyGV.DataBind();
}
}
protected void MyGV_RowCreated(object sender, GridViewRowEventArgs e) {
CheckBox MyCheckBox = (CheckBox)e.Row.FindControl("MyCheckBox");
if (isSomethingMarkedInDatabase) {
MyCheckBox.Checked = true;
}
}
protected void MyCheckBox_CheckedChanged(object sender, EventArgs e) {
CheckBox MyCheckBox = (CheckBox)sender;
if (MyCheckBox.Checked) {
// This is always run the first time a checkbox is clicked, whether or not it was checked or not in the first place. Any subsequent clicks on checkboxes has correct behaviour here.
} else {
}
}