在文本框上使用OnChange事件进行简单显示

时间:2013-05-26 13:11:45

标签: c# asp.net textbox onchange

如何在Textbox1和Textbox2中输入值后立即使用OnChange事件在Label1上显示结果?

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

         </div>
---------------------------------------------------------------------------------------
//Code behind

     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();

2 个答案:

答案 0 :(得分:3)

要使用TextChangedEvent,您需要在代码中添加TextChangedEvent事件处理程序,并在标记中设置AutoPostBack=true

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

背后的代码

    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();
    }

答案 1 :(得分:0)

这适用于两个文本框: -

<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>

代码背后:

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();
}