C# Public Variables

Learn how to use public variables in C#.

Have you ever wanted to have a variable available on another form than the one you declared it in?

You can use this if you have different buttons to show different things and don’t want to make a new form for each.

Start off with your buttons. For this tutorial, I’m going to use 3 buttons and a form that shows the button text.

First to declare your public variable use this:

public static string pvar;

This declares the variable as public.

Next, put this under each of your buttons’ click events. Edit the bart in Bold to your Button’s name.

pvar = Button1.Text;

Form f2 = new Form2();

f2.Show()

Next, open up your Form2 and add this under the load event

label1.Text = Form1.pvar;

This requires a label on Form2 to show the text of the variable.

Leave Your Response