0

I'm giving int input in Textbox1 and Textbox2, then the sum of both will be display on Label1. Can anyone show me how it work??? My int.parse not working.

.asxp

 <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>
         <asp:Button ID="Button1" runat="server" Text="Display" />

     </div>

.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MQM_System
{   
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            int sum = 0;

            sum = int.Parse(TextBox1.Text) + int.Parse(TextBox2.Text);
            Label1.Text = sum.ToString();
        }
    }
}
4

2 回答 2

1

您必须将 Button1_Click事件处理程序分配给Buttonevent OnClick

<asp:Button ID="Button1" runat="server" Text="Display" OnClick="Button1_Click" />

此外,您应该使用TryParse方法 ( msdn ) 而不是事件处理程序中的Parse方法。Button1_Click

于 2013-05-25T16:01:22.913 回答
0

Int.Parse 的问题在于它需要一个有效数字,否则会引发异常。
您可以使用 TryParse 来实现更好的控制

  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-25T15:53:13.990 回答