Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WPF
I am working on a textbox. I used a keydown event for handling pressed key. Now I need to do in my keydown event to interrupt the first char from 0. Suppose in my textbox I pressed 779. Now if I press 0 before 779, then I want to disable 0 that means e.handled=true. I could solved it if I will know length position of press key in that time. My code will like the following:
        private void txtBianry_KeyDown(object sender, KeyEventArgs e)
        {
            if (pressed key is of first length and 0 from full of text)
                 e.Handled = true;
 
            // continue...
        }
How can I solve this?
Thanks in advance.
Posted 12-Jan-13 6:18am
Comments
OriginalGriff at 12-Jan-13 11:38am
   
Answer updated
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Look at the TextBox.SelectionStart property - it gives the current caret position. If it is zero, and the SelectionLength is zero, the cursor is at the start and no text is selected.
 
[edit]
BTW: You don't want this in KeyDown - you want it in KeyPress:
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        if (tb.SelectionStart == 0 && tb.SelectionLength == 0 && e.KeyChar == '0')
            {
            e.Handled = true;
            }
        }
    }
[/edit]
  Permalink  
v2
Comments
Member 8454009 at 12-Jan-13 11:49am
   
your solution is great. And I am capable to use this code in my KeyDown event.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

I'd use a NumericUpDown. And There is at least one article on here showing how to do this. Failing that, can't you just check the Length of the existing value?
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 BillWoodruff 360
1 Mathew Soji 309
2 DamithSL 225
3 Afzaal Ahmad Zeeshan 202
4 Maciej Los 190
0 OriginalGriff 6,249
1 Sergey Alexandrovich Kryukov 5,853
2 DamithSL 5,183
3 Manas Bhardwaj 4,673
4 Maciej Los 3,865


Advertise | Privacy | Mobile
Web03 | 2.8.1411019.1 | Last Updated 12 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100