I'm creating a WPF application with a few input-text-fields and input should be checked if it contains only numbers and comma ( = convert to double must be possible) and so I have written the following code
private void txtBarauslagen_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return || e.Key == Key.Tab)
{
string text = txtBarauslagen.Text;
if (text != "") // nur wenn Feld nicht leer
{
try
{
double convtext = double.Parse(text);
MessageBox.Show(convtext.ToString());
// txtNotiz_int.Focus();
}
catch
{
MessageBox.Show("FALSCH - nicht nur Zahlen!");
txtBarauslagen.Text = "";
e.Handled = e.Key == Key.Tab;
}
}
}
}
The line "e.Handled = e.Key == Key.Tab;" is necessary because I have code in "LostFocus" which should only be executed if "convert to double" is possible.
I'd like to know if it is possible to change the line "txtBarauslagen.Text = "";" so that it is possible to refactor the code so that I can use the same code for another input-text-field. I have tried already to change it to "text.Text" in the catch-statement but that is not possible (I do not really know why).
To put it in a nutshell: I'd like to know if it is possible to retrieve the value for instance "txtBarauslagen.Text" or the object "txtBarauslagen" ( = my input-text-field) from "object sender).
CodePudding user response:
Since the sender is supposed to be the TextBox which raised that event, just cast it to TextBox and you can access its Text property.
TextBox tb = (TextBox)sender;
BTW, if I were you, I will use double.TryParse method instead.
CodePudding user response:
This is the revised code which is functioning properly, thank you
private void zeit1TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return || e.Key == Key.Tab)
{
TextBox tb = (TextBox)sender;
string TBSender = tb.Text;
double standVal = 0;
if (TBSender != "") // nur wenn Feld nicht leer
{
double.TryParse(TBSender, out standVal);
if (standVal != 0)
{
tb.Text = standVal.ToString();
}
else
{
MessageBox.Show("Nur Eingabe von Zahlen möglich!");
tb.Text = "";
e.Handled = e.Key == Key.Tab; // verhindert dass Focus weiterspringt
}
}
}
}
