C# Resize textbox to fit content

前端 未结 10 712
礼貌的吻别
礼貌的吻别 2020-12-05 13:39

I\'m writing a program where the user should be able to write text in a textbox. I\'d like the textbox to resize itself, so it fit the content. I\'ve tried the following:

10条回答
  •  孤城傲影
    2020-12-05 14:21

    first, create method to Make the TextBox fit its contents.

    private void AutoSizeTextBox(TextBox txt)
    {
        const int x_margin = 0;
        const int y_margin = 2;
        Size size = TextRenderer.MeasureText(txt.Text, txt.Font);
        txt.ClientSize =
            new Size(size.Width + x_margin, size.Height + y_margin);
    }
    

    then with the TextChanged event handler calls AutoSizeTextBox() function to make the TextBox fit its text when the text changes.

    private void txtContents_TextChanged(object sender, EventArgs e)
    {
        AutoSizeTextBox(sender as TextBox);
    }
    

    That’s all, for more info:

    resize-a-textbox-to-fit-its-text

提交回复
热议问题