日期:2014-05-18  浏览次数:21059 次

[真的很紧急]大家帮忙,如何让textbox根据自动调整高度?
代码如下:
  private void textBox1_TextChanged(object sender, EventArgs e)
  {
  TextBox textBox1 = (TextBox)sender;
  Graphics grp = textBox1.CreateGraphics();
  SizeF textsize = grp.MeasureString("啊", textBox1.Font);
  double length = 0;
  char[] c = textBox1.Text.ToCharArray();
  int i = textBox1.Text.Split('\r').Length + 1;
  Regex r = new Regex("[^\x00-\xff]");
  foreach (char cc in c)
  {
  Match m = r.Match(c.ToString());
  if (m.Success)
  {
  ++length;
  }
  else
  {
  length += 0.5;
  }
  }
   
  int width = (int)textsize.Width * 10;
  int height = (int)textsize.Height * (int)(length / 10 + i);
  textBox1.Size = new Size(width, height);
  grp.Dispose();
  }

这段代码测试算是成功,其中数字“10”是指定每行最多可输入10个字(为防止控件大小溢出),那么如何根据内容而自动调整高度?
这段代码测试时不稳定……请高手帮忙下。我这项目下礼拜4急用!!学校要用的……

------解决方案--------------------
根据内容自动调整滚动条的代码,照着改改应该能行
C# code

private void textBox5_TextChanged(object sender, System.EventArgs e)
        {
            TextBox tb=(TextBox) sender;
            ShowScrollBar(tb);
        }
private  void ShowScrollBar(TextBox tb)
        {
            //TextBox 当超出界面时显示垂直滚动条
            if(tb.Lines.Length>tb.Height/tb.Font.Height)
            {
                tb.ScrollBars=System.Windows.Forms.ScrollBars.Vertical;
            }
            else
            {
                tb.ScrollBars=System.Windows.Forms.ScrollBars.None;
            }
        }

------解决方案--------------------
private void textBox1_TextChanged(object sender, EventArgs e)
{
int t = getline();
Graphics g = this.textBox1.CreateGraphics();
SizeF ss = g.MeasureString("测试", this.textBox1.Font);
int h = (int)ss.Height + 3;
if (t <= 5)
{
this.textBox1.Height = t * h;
this.textBox1.ScrollBars = ScrollBars.None;
}
else
{
this.textBox1.Height = 5 * h;
this.textBox1.ScrollBars = ScrollBars.Vertical;
}
}
private int getline()
{
Graphics g = this.textBox1.CreateGraphics();
int lines=0;
foreach(string s in this.textBox1.Lines)
{
SizeF ss=g.MeasureString(s,this.textBox1.Font);
lines += ((int)ss.Width / this.textBox1.Width + 1);

}

return lines;
  
}