Get user input from a textbox in a WPF application

crossemup picture crossemup · Sep 14, 2015 · Viewed 79.3k times · Source

I am trying to get user input from the textbox in a WPF application I am building. The user will enter a numeric value and I would like to store it in a variable. I am just starting on C#. How can I do it?

Currently I am opening the textbox and letting the user enter the value. After that the user has to press a button upon which the text from textbox is stored in a variable.

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    var h = text1.Text;
}

I know this isn't right. What is the right way?

Answer

Leo Chapiro picture Leo Chapiro · Sep 14, 2015

Like @Michael McMullin already said, you need to define the variable outside your function like this:

string str;

private void Button_Click(object sender, RoutedEventArgs e)
{
    str = text1.Text;
}

// somewhere ...
DoSomething(str);

The point is: the visibility of variable depends on its scope. Please take a look at this explanation.