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();
}
}
}
You must assign Button1_Click
event handler to Button
event OnClick
.
<asp:Button ID="Button1" runat="server" Text="Display" OnClick="Button1_Click" />
Also you should use TryParse
method ( msdn ) instead of Parse
method in Button1_Click
event handler.
The problem with Int.Parse is that it requires a valid number otherwise it raises an exception.
You could use TryParse that allows for better control
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.