无法从 TextChanged 事件处理程序引用文本框的文本属性 [英] Can't refer to Text propery of textbox from TextChanged eventhandler
问题描述
我在 TextChanged 事件处理程序中获取文本框的 Text 值时遇到问题.
I have a problem with getting the Text value of a textbox in the TextChanged event handler.
我有以下代码.(简化)
I have the following code. (simplified)
public float varfloat;
private void CreateForm()
{
TextBox textbox1 = new TextBox();
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=new EventHandler(textbox1_TextChanged);
}
private void textbox1_TextChanged(object sender, EventArgs e)
{
varfloat = float.Parse(textbox1.Text);
}
我收到以下错误:当前上下文中不存在名称 textbox1".
I get the following error:'the name textbox1 does not exist in the current context'.
我可能在某个地方犯了一个愚蠢的错误,但我是 C# 新手,希望得到一些帮助.
I probably made a stupid mistake somewhere, but I'm new to C# and would appreciate some help.
提前致谢!
推荐答案
您已在 CreateForm
中将 textBox1
声明为 局部变量.变量只存在于该方法中.
You've declared textBox1
as a local variable within CreateForm
. The variable only exists within that method.
三个简单的选项:
使用 lambda 表达式在
CreateForm
中创建事件处理程序 :
Use a lambda expression to create the event handler within
CreateForm
:
private void CreateForm()
{
TextBox textbox1 = new TextBox();
textbox1.Location = new Point(67, 17);
textbox1.Text = "12.75";
textbox1.TextChanged +=
(sender, args) => varfloat = float.Parse(textbox1.Text);
}
将 sender
转换为 Control
并改用它:
Cast sender
to Control
and use that instead:
private void textbox1_TextChanged(object sender, EventArgs e)
{
Control senderControl = (Control) sender;
varfloat = float.Parse(senderControl.Text);
}
将 textbox1
改为实例变量.如果您想在代码中的任何其他地方使用它,这将很有意义.
Change textbox1
to be an instance variable instead. This would make a lot of sense if you wanted to use it anywhere else in your code.
哦,请不要使用公共字段:)
Oh, and please don't use public fields :)
这篇关于无法从 TextChanged 事件处理程序引用文本框的文本属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!