Reputation: 10199
I have a TextBox
that I define as:
<TextBox Name="input" HorizontalAlignment="Left" Height="0" Margin="155,110,-155,-110" TextWrapping="Wrap" VerticalAlignment="Top" Width="99"/>
<TextBox Height="25" Margin="126,85,-126,-110" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Width="99"/>
And I'm trying to access the value that is inside the TextBox
. I have tried to do this with:
int inputPax;
TextBox tb = (TextBox)this.FindName("input");
try
{
inputPax = int.Parse(tb.Text);
}
catch(System.FormatException)
{
inputPax = -9;
}
MessageBox.Show(inputPax.ToString());
And I'm always seeing the value as -9 no matter what my input is. What am I missing in order to read the value from the TextBox
correctly?
Upvotes: 0
Views: 47
Reputation: 116
I am not sure why you have a second textbox, and the first one has a height of 0. The second textbox that you are typing in is not the same as the first.
As for the second part, since you have created a textbox in the XAML that is named you can access its values by reference directly in your compiler, XAML is compiled in to C# and the compiler can recognise this.
I am also not sure why you want -9 as the integer value in the event of a failure, consider controlling the code some other way, possibly using a nullable int instead and checking for that or using an additional boolean value as shown below? Checking for a negative limits your choices, especially since its a user input, allowing an input of -9 can cause faults if your expecting -9 to represent a failure later on.
in short.
<TextBox Name="input" HorizontalAlignment="Left" Height="25" Margin="155,110,-155,-110" TextWrapping="Wrap" VerticalAlignment="Top" Width="99"/>
int inputPax;
bool result = int.TryParse(input.Text, out inputPax);
if (result)
{
MessageBox.Show($"{inputPax}");
//Interpolated $"strings" can be more succint and easier to modify.
}
else
{
MessageBox.Show("Input has failed to parse, please enter a number.");
}
Also consider adding an event to the textbox (click the lightning symbol in the properties window in your IDE and typing in a method name in PreviewTextInput or modifying the on the submit button click event for form input? Then you can use regex to test inputs to see if they match and if they do you can continue, if not then create error message and do not continue with the input process, allowing the user to alter their behaviour.
Edit 1: Also, even though I did not use any here, it might be a good idea to use more descriptive names than input, result, inputPax, etc. These days theres a lot of visual real estate on displays so having more descriptive names and ditching acronyms can help code legibility.
Upvotes: 1