代码之家  ›  专栏  ›  技术社区  ›  B. Clay Shannon-B. Crow Raven

如何动态地垂直扩展表单并将文本框向下移动适当的数量?

  •  2
  • B. Clay Shannon-B. Crow Raven  · 技术社区  · 13 年前

    我在表单上有一个标签和一个文本框。标签的内容是动态的,可能会溢出其边界到下面的文本框上。我想适当地动态增加表单的高度和文本框的顶部,以便标签内容将文本框“推”到表单上。通过将标签设置为“自动调整大小”并赋予其最大宽度,我想让它只水平生长到表单的右边缘,然后根据需要垂直(向下)生长。

    我尝试这样做的代码是:

    int bottomOfLabel = label1.Location.X + label1.Size.Height;
    int topOfTextBox = textBox1.Location.Y;
    int currentHeightOfForm = this.Size.Height;
    int currentTopOfTextBox = texBox1.Location.Y;
    
    if (bottomOfLabel >= topOfTextBox)
    {
        int heightToAdd = bottomOfLabel - topOfTextBox;
        this.Size.Height = currentHeightOfForm + heightToAdd;
        textbox.Location.Y = currentTopOfTextBox + heightToAdd;
    }
    

    …但我收到了以下错误:

    无法修改“System.Windows.Forms.Form.Size”的返回值,因为它不是变量

    -以及:

    无法修改“System.Windows.Forms.Control.Location”的返回值,因为它不是变量

    那么我该如何做到这一点呢?

    2 回复  |  直到 13 年前
        1
  •  4
  •   victorvartan    13 年前

    使用this.Height而不是this.Size.Height并使用textbox.Top而不是textbox.Location.Y。

        2
  •  0
  •   B. Clay Shannon-B. Crow Raven    13 年前
    const int WIGGLE_ROOM = 4;
    int bottomOfLabel = label1.Location.Y + label1.Size.Height;
    int currentHeightOfForm = this.Size.Height;
    int widthOfForm = this.Size.Width;
    int leftSideOfTextBox = textBox1.Location.X;
    int currentTopOfTextBox = textBox1.Location.Y;
    
    if (bottomOfLabel >= (currentTopOfTextBox - WIGGLE_ROOM)) {
        int heightToAdd = (bottomOfLabel - currentTopOfTextBox) + WIGGLE_ROOM;
        this.Size = new Size(widthOfForm, currentHeightOfForm + HeightToAdd);
         textBox1.Location = new Point(leftSideOfTextBox, currentTopOfTextBox +   
              heightToAdd);
    }
    
    推荐文章