Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
if there is 7 char in text box when the 8th one is enetered i want to delete the previos chars
Posted
Comments
Sergey Alexandrovich Kryukov 20-Apr-11 14:46pm    
Please, stop posting untagged Questions. Alway tag: WinForms, WPF, ASP.NET, etc. when UI is involved.
--SA

Instead of doing that, why not set the maximum length of the textbox?
Textbox1.MaxLength = 7;
That way, the user will not be allowed to key in more than 7 characters.
 
Share this answer
 
Comments
Mohammed Ahmed Gouda 20-Apr-11 4:16am    
no i want when the 8th char enter the text box i will take the first 7 char into DB
Sergey Alexandrovich Kryukov 20-Apr-11 14:48pm    
Think again.
--SA
Sergey Alexandrovich Kryukov 20-Apr-11 14:54pm    
Reasonable enough, my 5. OP's idea of having arbitrary length and cutting it to 7 has no practical grounds at all.
--SA
walterhevedeich 22-Apr-11 9:51am    
Thanks
Handle the TextBox.KeyPress event.
In the event, check the existing text, and modify if necessary.
private void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        string existing = tb.Text;
        if (existing.Length >= 7)
            {
            tb.Text = existing.Substring(existing.Length - 6);
            tb.SelectionStart = tb.Text.Length;
            }
        }
    }
 
Share this answer
 
Comments
nit_singh 20-Apr-11 6:37am    
This solution is nice but we can handle this in javascript so that the page wont be refreshed.
OriginalGriff 20-Apr-11 8:11am    
In which case, it might be worth tagging your question so we know it is web based in future?
Rojeh 20-Apr-11 8:12am    
my 5
Prasanta_Prince 20-Apr-11 8:46am    
Good Solution
Sergey Alexandrovich Kryukov 20-Apr-11 14:55pm    
You correctly follow the requirement by OP, but the requirement is completely unreasonable as I can see from the comments, so why doing all that?
--SA
I think you want to remove all previous 7 chars, you can use bellow
C#
if (textBox1.Text.Length > 7)
{
   textBox1.Text = textBox1.Text.Remove(0, 7);
   textBox1.SelectionStart = textBox1.Text.Length;
}
 
Share this answer
 
if you want to get the first 7 characters (to use it) and delete it from the text:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            string FirstSeven;
            if (textBox1.Text.Length >= 7)
            {
                FirstSeven = textBox1.Text.Substring(0, 7);
                textBox1.Text = textBox1.Text.Substring(7);
            }
         }
 
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