C# How to make a text box a global variable

BBQMemphis used Ask the Experts™
I have a text box and button on a windows form that I want the end user to enter information.  I want to be able to call that information from any other part of the program.  In other words I want to make a public string that would be this.txtWidth.text

In other words I want the user to enter the width in a tex box of a windows form.

But be able to call that width from any other form or part of the program

Thanks in advance for your help
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

you have to create some static variable in a static class, and save the value in there:

Software Architect
Top Expert 2008
I wouldn't suggest a static qualifier for a control.
A control use to belong to an specific form instance, so it is just needed to make it public. Controls are not public by default. So, go to your form designer, select the textbox, and change Modifier property to Public.
Now you need a reference to your form. The form itself can be a static reference in your Application class.
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

>I wouldn't suggest a static qualifier for a control.
neither did I :)
Slim chance that you want want the value from the textbox if the form is closed...Maybe you have a scoping issue...Go to the designer of the form and change its private scope to public. Then where ever you have an instance of the form, you can then say: string name = frmMain.txtReachable

If you need it when closed, try writing the value to the appsettings from the Form_Closing event.

To expand on what angellll suggested, the static class and variable are to contain the value entered by the user, not the control itself. Create a class as in the attached code snippet, and then wherever you have the user submit the value of the textbox simply use the following to persist the value:

GlobalValues.UserWidth = TextboxWidth.Text;

Replacing the "TextboxWidth" part with the name of your textbox. Now when you need to access the value, you can do so as such:

string myString = GlobalValues.UserWidth;
// A static class with a static variable to persist the width entered 
// by the user on a form.
public static class GlobalValues
    public static string UserWidth = ""; 
    public GlobalValues(){}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial