如何从按钮单击事件处理程序访问文本框中的文本

时间:2015-02-25 03:20:10

标签: c# winforms

我试着写这个简单的winform菜单,我需要将NBox文本框的内容添加到字符串中,这样我可以在按下按钮时显示它,但是我不断收到NBox不存在的错误目前的背景。那么,如何通过按下按钮来获取文本框的内容呢?

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
//namespace game{
class MainM : Form{

public MainM(){

    Text = "Adventures Main Menu";
    Size = new Size(400,400);

    //NameBox
    TextBox NBox = new TextBox();
    NBox.Location = new Point(145, 100);
    NBox.Size = new Size(200, 30);

    //Title Label

    Label title = new Label();
    title.Text = "ADVENTURE THE GAME";
    title.Location = new Point(145, 30);
    title.Size =  new Size(200,60);
    title.Font = new Font(defaultFont.FontFamily, defaultFont.Size, FontStyle.Bold);

    //The main menu Buttons and all that jazz
    Button credits = new Button();
    Button start = new Button();

    //Credits Button
    credits.Text = "Credits";
    credits.Size = new Size(75,20);
    credits.Location = new Point(145,275);
    credits.Click += new EventHandler(this.credits_button_click);

    //Start Button
    start.Text = "Start";
    start.Size = new Size(75,20);
    start.Location = new Point(145,200);
    start.Click += new EventHandler(this.start_button_click);


    //Control addition
    this.Controls.Add(title);
    this.Controls.Add(credits);
    this.Controls.Add(start);
    this.Controls.Add(NBox);
}

  public void test(){
            //The Main Window
  }

  private void credits_button_click(object sender, EventArgs e){
    MessageBox.Show("Created by: Me");
  }

 private void start_button_click(object sender, EventArgs e){
    this.Hide();
    string name = NBox.Text;
    MessageBox.Show(name);

    //Process.Start("TextGame.exe");
 }

  public static void Main(){
    Application.Run(new MainM());
  }

} 
//}

2 个答案:

答案 0 :(得分:0)

首先,您需要命名控件,该名称将是容器的Controls集合中的键:

//NameBox
TextBox NBox = new TextBox();
NBox.Location = new Point(145, 100);
NBox.Size = new Size(200, 30);
NBox.Name = "NBox"; //Naming the control

然后您就可以从容器中检索它了:

private void start_button_click(object sender, EventArgs e){
    this.Hide();
    TextBox NBox= (TextBox)Controls.Find("NBox", true)[0];//Retrieve controls by name        
    string name = NBox.Text;
    MessageBox.Show(name);
    //Process.Start("TextGame.exe");
}

答案 1 :(得分:0)

您在构造函数中声明了NBox,它只在构造函数中可见。你需要将它移到构造函数之外。

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
//namespace game{
class MainM : Form{
    TextBox NBox;

    public MainM(){

    Text = "Adventures Main Menu";
    Size = new Size(400,400);

    //NameBox
    NBox = new TextBox();
    ...