Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I manage a TextBox which user can input just Integer characters and backspace key. Also this characters would be separated on third position like this(921,323,456).
the problem is in middle of number when I press backspace the character would be delete but cursor position will go to first position of first input integer. for example in number above when I delete char '4' the cursor position will go to char '9'.

function for separating numbers:
C#
 public static void SpiltOnThird_TextChanged(object sender, EventArgs e)
{
        TextBox txb = (TextBox)sender;
        txb.Text=numberSpiltOnThird(txb.Text);
        txb.Select(txb.Text.Length, 0);
}
 public static string numberSpiltOnThird(string num)
{
    if (num != ("0") & !string.IsNullOrEmpty(num))
    {
        NumberFormatInfo nfi = new NumberFormatInfo();
        num = num.Replace(",", "");
        num = Convert.ToInt64(num).ToString();
        nfi.NumberDecimalDigits = 0;
        return decimal.Parse(num).ToString("n", nfi);
    }
    else
        return "";
}
Posted

why don't you use masking of textbox,

and then on keypress event on particular textbox use the above code

C#
if (!char.IsNumber(e.KeyChar) && e.KeyChar.ToString() != "\b")
            {
                e.Handled = true;
            }


hope dis helps :)
 
Share this answer
 
The current caret position (the "I" beam that indicates the user input position, "cursor" is a different beastie) in a text box isn't obvious - it's the SelectionStart index value. So read it first, so you know where he was, and you can set it afterwards to put him where you want him.
 
Share this answer
 
Comments
mit62 29-May-14 14:50pm    
Thanks. I changed TextChanged Function.
public static void SpiltOnThird_TextChanged(object sender, EventArgs e)
{
TextBox txb = (TextBox)sender;
int caretIndex = txb.SelectionStart;
txb.Text=numberSpiltOnThird(txb.Text);
txb.Select(caretIndex, 0);
}

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