Click here to Skip to main content
15,926,290 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C#
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
Comments
OriginalGriff 12-Jan-13 11:38am    
Answer updated

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:
C#
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]
 
Share this answer
 
v2
Comments
Member 8454009 12-Jan-13 11:49am    
your solution is great. And I am capable to use this code in my KeyDown event.
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?
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900