CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2005
    Posts
    59

    Thumbs up characters upto control width

    how should we restrict characters typed in a control to its width only.

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: characters upto control width

    Put an event handler in for the "TextChanged" event.

    Then, get the text out of the text box and measure it.

    I'd have an inherited class to do this :

    Code:
    public class WidthLimitTextBox : TextBox
    {
        private string m_sOldText = "";
        private bool m_fHandleTextChanged = true;
    
        protected override OnTextChanged(EventArgs e)
        {
            if (m_fHandleTextChanged)
            {
                m_fHandleTextChanged = false;
    
                using (Graphics graphics = this.CreateGraphics())
                {
                    Size sizeText = graphics.MeasureString(this.Text, this.Font).ToSize();
    
                    if (sizeText.Width > this.ClientRectangle.Width)
                    {
                        this.Text = m_sOldText;
                    }
                    else
                    {
                        m_sOldText = this.Text;
                    }
                }
        
                m_fHandleTextChanged = true;
            }
        }
    }
    I've not tried this out, but it should give you a rough idea of how to do it.

    Darwen.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  3. #3
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Thumbs up Re: characters upto control width

    There is a maxlength attribute for the html textboxes. I am not sure about the server side controls but u might need to write some javascript validations to restrict the user from doing this. The server side control has a size property though, that sets or returns the expected length of the specified text box, in characters. The default value for the size of a text box is 0, which means that the browser will use its default text box length.
    Quote Originally Posted by MSDN
    This information is not used to perform validation checks against the actual input value. To perform a validation check against an input value, use the validator controls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured