C# Resize textbox to fit content

前端 未结 10 711
礼貌的吻别
礼貌的吻别 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:22

    Your binding to the wrong event, and you cannot use the graphics object in the TextChangedEventArgs object.

    Try using the TextChanged event. The following snippet is working:

    public Form1()
    {
        InitializeComponent();
    
        this.textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
    }
    
    void textBox1_TextChanged(object sender, EventArgs e)
    {
        System.Drawing.SizeF mySize = new System.Drawing.SizeF();
    
        // Use the textbox font
        System.Drawing.Font myFont = textBox1.Font;
    
        using (Graphics g = this.CreateGraphics())
        {
            // Get the size given the string and the font
            mySize = g.MeasureString(textBox1.Text, myFont);
        }
    
        // Resize the textbox 
        this.textBox1.Width = (int)Math.Round(mySize.Width, 0);
    }
    

    }

提交回复
热议问题