Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't We get Current value of Text Box in PreviewKeyDown Event?

Tags:

c#

wpf

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
        { }
    }      
like image 257
Sagar Avatar asked Jan 07 '23 02:01

Sagar


2 Answers

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.

like image 168
javirs Avatar answered Jan 10 '23 12:01

javirs


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 { }     
}

}

like image 41
StepUp Avatar answered Jan 10 '23 11:01

StepUp