And*_*i S 16 c# textbox resize
在C#表单中,我有一个面板固定在所有侧面,并在内部,一个文本框,锚定顶部/左/右.
当文本加载到文本框中时,我希望它自动垂直展开,这样我就不需要滚动文本框(如果有更多文本不适合面板,最多滚动面板).有没有办法用文本框这样做?(我不限制使用此控件,所以如果有另一个符合描述的控件,请随意提及)
Dav*_*ret 29
当前选择的答案不处理没有空格的行,例如"jjjjjjjjjjjjjjjjjjjjj"x1000(想想如果有人粘贴了URL会发生什么)
此代码解决了这个问题:
private void txtBody_TextChanged(object sender, EventArgs e)
{
    // amount of padding to add
    const int padding = 3;
    // get number of lines (first line is 0, so add 1)
    int numLines = this.txtBody.GetLineFromCharIndex(this.txtBody.TextLength) + 1;
    // get border thickness
    int border = this.txtBody.Height - this.txtBody.ClientSize.Height;
    // set height (height of one line * number of lines + spacing)
    this.txtBody.Height = this.txtBody.Font.Height * numLines + padding + border;
}
Han*_*ant 25
我假设这是一个多行文本框,你可以让它垂直增长.这段代码效果很好:
    private void textBox1_TextChanged(object sender, EventArgs e) {
        Size sz = new Size(textBox1.ClientSize.Width, int.MaxValue);
        TextFormatFlags flags = TextFormatFlags.WordBreak;
        int padding = 3;
        int borders = textBox1.Height - textBox1.ClientSize.Height;
        sz = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, sz, flags);
        int h = sz.Height + borders + padding;
        if (textBox1.Top + h > this.ClientSize.Height - 10) {
            h = this.ClientSize.Height - 10 - textBox1.Top;
        }
        textBox1.Height = h;
    }
当文本框为空时,您应该做一些合理的事情,比如设置MinimumSize属性.