2

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

2 回答 2

4

要使用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();
    }
于 2013-05-26T13:17:02.570 回答
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();
}
于 2013-05-26T13:25:56.183 回答