Simple display with OnChange event on textbox

ぃ、小莉子 提交于 2019-12-08 20:00:33

To use TextChangedEvent you need to add TextChangedEvent event handler in your code and set AutoPostBack=true in markup

<asp:TextBox ID="TextBox2" runat="server" OnTextChanged="TextBox2_TextChanged" AutoPostBack="true"></asp:TextBox>

Code behind

    protected void TextBox2_TextChanged(object sender,EventArgs e)
    {
       int num1;
       if(!Int32.TryParse(TextBox1.Text, out num1))
       {
          Label1.Text = "Not a valid number";
          return;
       }
       int num2;

      if(!Int32.TryParse(TextBox2.Text, out num2))
      {
         Label1.Text = "Not a valid number";
         return;
      }
      sum = num1 + num2;
      Label1.Text = sum.ToString();
    }

This will work for both textboxes :-

<div>
         <asp:TextBox ID="TextBox1" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
         <asp:TextBox ID="TextBox2" OnTextChanged="AnyTextBox_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
         <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>

Code behind:

protected void AnyTextBox_TextChanged(object sender, EventArgs e)
{
    int sum = 0;
    int num1;
    if (!Int32.TryParse(TextBox1.Text, out num1))
    {
        Label1.Text = "Not a valid number";
        return;
    }
    int num2;

    if (!Int32.TryParse(TextBox2.Text, out num2))
    {
        Label1.Text = "Not a valid number";
        return;
    }
    sum = num1 + num2;
    Label1.Text = sum.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!