C# 在文本框上使用 OnChange 事件简单显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16759568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple display with OnChange event on textbox
提问by CoderBeginner
How to use the OnChange event to display the result on the Label1 instantly after value have enter in Textbox1 and Textbox2??
在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();
采纳答案by Sachin
To use TextChangedEventyou need to add TextChangedEventevent handler in your code and set AutoPostBack=truein markup
要使用,TextChangedEvent您需要TextChangedEvent在代码中添加事件处理程序并AutoPostBack=true在标记中设置
<asp:TextBox ID="TextBox2" runat="server" OnTextChanged="TextBox2_TextChanged" AutoPostBack="true"></asp:TextBox>
Code behind
背后的代码
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();
}
回答by tariq
This will work for both textboxes :-
这适用于两个文本框:-
<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>
Code behind:
后面的代码:
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();
}

