Super Girl Super Girl - 1 month ago 7
ASP.NET (C#) Question

CheckedChanged event is not fired

In my

WebForm
I want the total price changed when the user check one product but I have this problem with my code ,

the
CheckedChanged
event is not firing when I check the
CheckBox


It is firing only when I click the
Button
(used for as clear button) , and I didn't include that code within the button event !

Here is my code:

public partial class _Default : System.Web.UI.Page
{
int total = 0;
String strtotal;

protected void ckb1_CheckedChanged(object sender, EventArgs e)
{
if (ckb1.Checked)
{
total = total + 100;
strtotal = total.ToString();
lbl2.Text = strtotal;
}

}

protected void ckb2_CheckedChanged(object sender, EventArgs e)
{
if (ckb2.Checked)
{
total = total + 80;
strtotal = total.ToString();
lbl2.Text = strtotal;
}
}

protected void ckb3_CheckedChanged(object sender, EventArgs e)
{
if (ckb3.Checked)
{
total = total + 70;
strtotal = total.ToString();
lbl2.Text = strtotal;
}
}

protected void Button3_Click(object sender, EventArgs e)
{
TextBox1.Text = " ";
ckb1.Checked = false;
ckb2.Checked = false;
ckb3.Checked = false;
}

}

Answer

All ASP.NET Server controls except Button, Hyperlink and LinkButton have a default AutoPostBack property of false, So you should set AutoPostBack="true" in your CheckBox:

<asp:CheckBox ID="ckb1" runat="server" AutoPostBack="true" OnCheckedChanged="ckb1_CheckedChanged" />

It is firing only when I click the button

As I said this is because the Button have AutoPostBack property of true by default so after you checked the CheckBox and then click the button the CheckBox state automatically posts back to the server.