Reputation: 4418
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?
<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>
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 {
}
}
Upvotes: 1
Views: 896
Reputation: 460028
Why do you use RowCreated
instead of RowDataBound
? RowCreated
is always triggered, so on each and every postback, before the events are triggered. So maybe it is fixed if you move that code to RowDataBound
which is only called after grid.DataBind()
.
protected void MyGV_RowDataBound(object sender, GridViewRowEventArgs e) {
if (row.RowType == DataControlRowType.DataRow){
CheckBox MyCheckBox = (CheckBox)e.Row.FindControl("MyCheckBox");
MyCheckBox.Checked = isSomethingMarkedInDatabase;
}
}
You can access the datasource in RowDataBound
. If you want to evaluate a field in the record you have to cast e.Row.DataItem
to the actual type(f.e. a DataRowView
).
Upvotes: 1