I am trying to read Current value of Text Box in PreviewKeyDown Event but unable to get current value.
Here is my code ,
private void txtDoscountValue_PreviewKeyDown(object sender, KeyEventArgs e)
{
try
{
if (txtDoscountValue.Text == string.Empty)
discountPercentage = 0;
else
discountPercentage = float.Parse(txtDoscountValue.Text);
CalculateCart(cartItems, discountPercentage, 0);
}
catch
{ }
}
Maybe your problem is that you are asking at PreviewKeyDown
, so when it gets called, there is still no values in the box. If you want to get called when the box actually changes you need to hook to KeyDown
or even better TextChanged
.
PreviewKeyDown
is for checking the content of the change before actually applying it, which is kind of validation.
The value of the modification is stored in the keyEventArgs
, not in the textbox.
It is possible to read value of TextBox at any time with Text
property of TextBox
control:
var currentValue=textBox.Text;
To read inputted keys
of keyboard, you can use e.Key
of KeyEventArgs
:
private void txtDoscountValue_PreviewKeyDown(object sender, KeyEventArgs e)
{
try
{
string input=e.Key;
var ee = txtDoscountValue.Text;
}
catch { }
}
Update:
It is possible to use KeyConverter
class to convert Keys
to string. You should add reference to assembly System.Windows.Forms to your WPF project to use KeyConverter
class:
private void textBox1_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
try
{
char c = '\0';
System.Windows.Input.Key key = e.Key;
if ((key >= Key.A) && (key <= Key.Z))
{
c = (char)((int)'a' + (int)(key - Key.A));
}
else if ((key >= Key.D0) && (key <= Key.D9))
{
c = (char)((int)'0' + (int)(key - Key.D0));
}
else if ((key >= Key.NumPad0) && (key <= Key.NumPad9))
{
c = (char)((int)'0' + (int)(key - Key.NumPad0));
}
//here your logic
}
catch { }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With