Huizhong Xu
Huizhong Xu

Reputation: 35

ASP.NET checkbox autopostback not working

I designed a simple page with, two text boxes, one checkbox, one button, and one label.

When I start I want to check the checkbox to make the button enabled, and then enter two numbers into the two textboxes, click the button to do addition, and show the result in the label.

But when I click the checkbox the page postback is not working; it's not writing Page is posted back on the page and the button is still disabled.

However, if I make the button enabled and do the addition it invokes the page postback and also invokes the checkedchanged method.

<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<asp:Label ID="result" runat="server"></asp:Label>

<td>
    <asp:CheckBox ID="cboptions" runat="server" AutoPostBack="True"   
        onCheckedChanged="cboptions_CheckedChanged" />
</td>

<asp:Button ID="submit" runat="server" Text ="addition" onclick="Button_Click"/>

Code:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack == true)
    {
        Response.Write("Page is posted back");
    }
}
protected void cboptions_CheckedChanged(object sender, EventArgs e)
{
    submit.Enabled = cboptions.Checked;
}
protected void submit_Click(object sender, EventArgs e)
{
    int a = Convert.ToInt32(txtFirst.Text);
    int b = Convert.ToInt32(txtSecond.Text)+a;
    result.Text = b.ToString();
}

Upvotes: 2

Views: 13265

Answers (1)

Sid M
Sid M

Reputation: 4354

There were many formatting errors in your code, do it this way

Aspx

 <asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<asp:Label ID="result" runat="server"></asp:Label>
<asp:CheckBox ID="cboptions" runat="server" AutoPostBack="True" 
  onCheckedChanged="cboptions_CheckedChanged" />
<asp:Button ID="btn" runat="server" Text ="addition" onclick="Button_Click"/>

C#

 protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == true)
            {
                Response.Write("Page is posted back");
            }
        }

        protected void cboptions_CheckedChanged(object sender, EventArgs e)
        {
            btn.Enabled = cboptions.Checked;
        }
        protected void Button_Click(object sender, EventArgs e)
        {
            int a = Convert.ToInt32(txtFirst.Text);
            int b = Convert.ToInt32(txtSecond.Text) + a;
            result.Text = b.ToString();
        }

Upvotes: 4

Related Questions