Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user input from a textbox in a WPF application

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?

like image 298
crossemup Avatar asked Sep 14 '15 10:09

crossemup


People also ask

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.

What is data binding WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

How do I add a TextBox in XAML?

Here's how to create a TextBox in XAML and in code. TextBox textBox = new TextBox(); textBox. Width = 500; textBox. Header = "Notes"; textBox.


1 Answers

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.

like image 108
Leo Chapiro Avatar answered Sep 19 '22 01:09

Leo Chapiro