TextBox classes do not have thie method: set_AutoSize(true)

Why is this that set_AutoSize(true) method is not available to TextBoxes, but is available to Labels.

What would be the alternate method to be used for TextBoxes.

Thanks




Answer this question

TextBox classes do not have thie method: set_AutoSize(true)

  • dmssjt

    I did it by a slight trick.The trick is to create a custom TextBox which inherits from textbox.Then we create a private label and set its font to the textbox font and set its autoresize to true.When we set the text of the textbox,we set the labels text to the same.Then we query for the label' s dimensions and set it to the textbox.

    public class AutoSizeTextBox : TextBox

    {

    private Label l = new Label();

    public AutoSizeTextBox()

    {

    l.AutoSize = true;

    l.Font = base.Font;

    //Get notification when font changes

    this.FontChanged += new EventHandler(ChangedFont);

    //

    // TODO: Add constructor logic here

    //

    }

    private void ChangedFont(object sender, EventArgs e)

    {

    Control c = sender as Control;

    //update labels font

    l.Font = c.Font;

    }

    public new string Text

    {

    get

    {

    return base.Text;

    }

    set

    {

    base.Text = value;

    l.Text = value;

    Width = l.Width;

    Height = l.Height;

    }

    }

    }


  • Stanley Daniel

    Because it makes sense for a label to size itself according to it's text, all it does is display text. For a textbox to resize itself as you type would be weird.

    The Width property on the textbox lets you resize it and the MeasureString method on the Graphics object would let you work out how long a string is.



  • Ken Elmy

    Thanks for your reply.

    I will test your class. Basically I am trying to create an "editable label" -- flat & without a border -- user can start editing/entering text in it by double clicking it; and ending the editing by clicking somewhere else, or pressing enter; and WHILE entering text, ALL text inside the text box must be visible. This editable label could occur in the middle of other "uneditable" texts (real labels) which would shift automatically as length of the text increases or decreases.

    But when I did similar subclassing, whenever I enter "1234" on the text box, always the first character would not be visible, sometimes two characters. I padded with extra spaces, but still the first 1 or 2 characters still invisible despite having plenty of space at the right. And I do not want extra space because I would like this text to blend with the "uneditable" text before and after it (just like editing in MS Word).

    As an alternative, I could use a RichTextBox where only selected portions are editable to the user - not the whole text. I am not sure such functionality exists in a RichTextBox or any other class. If you know any, let me know.

    Thank.



  • TextBox classes do not have thie method: set_AutoSize(true)