Setting a limit for the textbox . . .

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CodeNoobster
    New Member
    • Sep 2013
    • 52

    Setting a limit for the textbox . . .

    Hey everyone, little problem here, I have managed to make text dynamically appear in a text-box while I enter text into another.

    how ever I would like to know to to limit the amount of text that is dynamically entered(I'd say about 10 characters at most). Any suggestions and help would be greatly appreciated!

    here's a sample of what I have done so far:

    Code:
    Random r = new Random();
    int IDrandom = r.Next(0, 9);
    Emp_ID.Text += IDrandom.ToString();
    
    //Emp_ID.MaxLength = 10; does not work
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    in the specification of TextBox


    it states
    In code, you can set the value of the Text property to a value that has a length greater than the value specified by the MaxLength property. This property only affects text entered into the control at run time.

    hence the MaxLength property does not work as you expect

    after you have added the latest character to Emp_ID.Text could you read the Emp_ID.Text property as a String and use the String.Remove() method to delete all but the last 10 characters then write it back into Emp_ID.Text

    Comment

    • CodeNoobster
      New Member
      • Sep 2013
      • 52

      #3
      Thanks horace1 that helps. thumbs up

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        in fact as you are only adding one character at a time you only need to delete the first character, e.g.
        Code:
        Emp_ID.Text += IDrandom.ToString();
        string s = Emp_ID.Text;
        if (s.Length > 10) s=s.Remove(0, 1);
        Emp_ID.Text=s;

        Comment

        Working...