在我的WebForm中,我希望在用户检查一个产品时总价格发生变化,但我的代码存在此问题,
检查CheckBox时,CheckedChanged事件没有触发
它只在我单击按钮(用作清除按钮)时触发,并且我没有在按钮事件中包含该代码!
这是我的代码:
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; } }
解决方法
除Button,Hyperlink和LinkButton之外的所有ASP.NET Server控件都具有默认的AutoPostBack属性,因此您应该在CheckBox中设置
AutoPostBack="true"
:
<asp:CheckBox ID="ckb1" runat="server" AutoPostBack="true" OnCheckedChanged="ckb1_CheckedChanged" />
It is firing only when I click the button
正如我所说,这是因为默认情况下Button的AutoPostBack属性为true,因此在您选中CheckBox然后单击按钮后,CheckBox状态会自动回发到服务器.