很抱歉noob问题...我想在每次点击按钮时将TextBox的内容输出到控制台。我的TextBox变量“textBox”没有被看到,因为我认为它超出了范围。我想知道正确的方法是什么。
谢谢。
class Test : Form
{
public Test()
{
Button btn = new Button();
btn.Text = "Click Me";
btn.Parent = this;
btn.Location = new Point(100, 10);
btn.Click += ButtonOnClick;
TextBox textBox = new TextBox();
textBox.Parent = this;
textBox.Size = new Size(150, 25);
textBox.Location = new Point(60, 60);
}
void ButtonOnClick(object objSrc, EventArgs args)
{
String message = textBox.Text;
Console.WriteLine(message);
}
}
class Driver
{
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Test());
}
}
}
答案 0 :(得分:2)
WinForms应用程序没有要写入的控制台。因此,在Visual Studio的调试会话之外,您永远不会看到任何提供捕获Console.WriteLine输出的窗口的内容 您可以将控制台添加到WinForms应用程序,但这是完全不同的事情
How do I show a Console output/window in a forms application
说,你的问题是由于你为你的控件创建了两个局部变量,但是你没有将它们添加到窗体控件容器然后从构造函数中退出而丢失两个变量。
您应该为这些控件保留全局类级变量
class Test : Form
{
private Button btn;
private TextBox textBox;
public Test()
{
btn = new Button();
btn.Text = "Click Me";
btn.Parent = this;
btn.Location = new Point(100, 10);
btn.Click += ButtonOnClick;
this.Controls.Add(btn);
textBox = new TextBox();
textBox.Parent = this;
textBox.Size = new Size(150, 25);
textBox.Location = new Point(60, 60);
this.Controls.Add(textBox);
}
void ButtonOnClick(object objSrc, EventArgs args)
{
String message = textBox.Text;
// This will be written to the Output Window when you debug inside
// Visual Studio or totally lost if you run the executable by itself
//Console.WriteLine(message);
// WinForms uses MessageBox.Show
MessageBox.Show(message);
}
}
当您向表单添加控件时,这是您可以在表单设计器为您编写的InitializeComponent中找到的代码