mercredi 25 février 2015

How do I access the text in a text box from a button click event handler

Im trying to write this simple winform menu and I need to add the contents of the NBox text box to a string so I can display it when a button is pressed, however I keep getting the error that NBox does not exist in the current context. So, how would i got about making the contents of the text box available at the press of a button?



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());
}

}
//}

Aucun commentaire:

Enregistrer un commentaire