2012-09-17 40 views
-1

我在TextChanged事件处理程序中获取文本框的Text值时遇到问题。无法从TextChanged事件处理程序中引用文本框的文本

我有以下代码。 (简体)

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在当前上下文中不存在'。

我可能在某个地方犯了一个愚蠢的错误,但我是C#的新手,希望得到一些帮助。

在此先感谢!

回答

2

您已经声明textBox1局部变量CreateForm。该变量只存在于该方法内。

三个简单的选择:

  • 使用lambda表达式中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); 
    } 
    
  • 铸造senderControl并使用它:

    private void textbox1_TextChanged(object sender, EventArgs e) 
    { 
        Control senderControl = (Control) sender; 
        varfloat = float.Parse(senderControl.Text); 
    } 
    
  • textbox1更改为实例变量。如果你想在你的代码的其他任何地方使用它,这将会很有意义。

哦,请不要使用公共字段:)

0

定义textbox1在类级作用域而不是函数作用域的外侧CreateForm(),以便它可用于textbox1_TextChanged事件。

TextBox textbox1 = new TextBox(); 

private void CreateForm() 
{  
     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); 
} 
+0

很好的建议做了,谢谢。 –

+0

不客气。 – Adil

1

试试这个:

private void textbox1_TextChanged(object sender, EventArgs e) 
{ 
    varfloat = float.Parse((sender as TextBox).Text); 
} 
+0

你知道'sender'参数将会是一个文本框,所以你应该只说'(TextBox)sender'。 – siride

+0

@siride,两者都是一样的我不这么认为它的行为有所不同 –

+0

它们实际上并不相同,因为它执行类型检查,然后执行类型转换,而我只执行类型转换。如果结果是发件人不是TextBox的情况下,你的方法将抛出一个空引用异常,并且我会抛出适当的类型转换异常。最后,我的方法恰当地记录了意图和期望。 – siride

0

您没有添加文本框控件到窗体。

它可以作为

TextBox txt = new TextBox(); 
txt.ID = "textBox1"; 
txt.Text = "helloo"; 
form1.Controls.Add(txt); 
+0

For more info http://stackoverflow.com/questions/4665472/using-dynamically-created-controls-in-c-sharp – Pushpendra

+0

这当然是原始代码中的一个问题,但这不是OP问的问题关于。 – siride

+0

如果控件是动态创建的,则必须将其添加到表单中,否则它将无法访问。 纠正我,如果我错了。 – Pushpendra

相关问题