uzi42tmp
uzi42tmp

Reputation: 291

How to pass variable from event method?

I have a event method private void button1_Click_1(object sender, EventArgs e) with some code in it. There I want to use a variable from another event method called public void textBox2_TextChanged(object sender, EventArgs e)

so if a user writes a number it gets saved in a variable in the second method and i want to use this variable in the first method where a button gets clicked. How do I pass it?

Upvotes: 0

Views: 252

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

Save it as a field of your form class. You can then write it in one event handler and read it in another:

public partial class MyForm
{
    private string _someValue = null;

    public void TextBox2_TextChanged(object sender, EventArgs e)
    {
        _someValue = "Some New Value";
    }

    public void Button1_Click(object sender, EventArgs e)
    {
        if (_someValue != null)
        {
            // ...
        }
    }   
}

Though perhaps you can just read TextBox2.Text in the second method.

Upvotes: 2

Related Questions