本文介绍了在文本框上使用OnChange事件进行简单显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用OnChange事件在Textbox1和Textbox2中输入值后立即在Label1上显示结果?
How to use the OnChange event to display the result on the Label1 instantly after value have enter in Textbox1 and Textbox2??
<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();
推荐答案
要使用TextChangedEvent
,您需要在代码中添加TextChangedEvent
事件处理程序,并在标记中设置AutoPostBack=true
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>
后面的代码
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();
}
这篇关于在文本框上使用OnChange事件进行简单显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!