Jarred Sumner
Jarred Sumner

Reputation: 1853

C# Get Variable Value from Separate Form

How can I get the values of variables from a separate form?

Upvotes: 1

Views: 7351

Answers (5)

murasaki5
murasaki5

Reputation: 856

You just need to add the following code in the other form if you want to get a specific value of a variable for instance a textbox... Note that the variable text is declared to who will receive the value and that it is static.

public Form2(string text)
{
     InitializeComponent();
     text = textBox.text;
}

Upvotes: 1

shahjapan
shahjapan

Reputation: 14335

if you want to read the values of few variables you can go with the solution provided by CesarGon.

Its simple you can get the values of properties like Form2.Count and so on...while your form is not disposed.

You can create a method returning Hashtable which will contain the values you want to return. for example

public Hashtable GetData()
{
     Hashtable ht = new Hashtable();
     ht.add('count',textBox1.Text);

     return ht;
}

If you want to pass values of one form to another form you can pass them from the constructor of second form.

Upvotes: 0

Mike Cole
Mike Cole

Reputation: 14703

You can also pass in your values in an overloaded constructor of your instantiated form.

Upvotes: 0

msha
msha

Reputation: 163

As long as the other form is running and the variable is accessible (public) that you just need to pass the reference to the form.

Upvotes: -1

CesarGon
CesarGon

Reputation: 15325

You can expose them through properties.

For example, if form Form2 has a variable named _Count of type int, you can create a property like this:

public int Count
{
    get { return _Count; }
}

Then you can access that property on Form2 instances.

Upvotes: 6

Related Questions