我在表单上有一个标签和一个textBox。标签的内容是动态的,可以将其边界溢出到它下面的文本框中。我想根据需要动态增加表单的高度和textBox的顶部,以便标签内容“按下”表单上的文本框。通过将标签设置为自动调整大小并赋予其最大宽度,我希望允许它仅水平增长到窗体的右边缘,然后垂直(向下)尽可能多地增长。
我尝试此操作的代码是:
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'的返回值,因为它不是变量
那我怎么能做到这一点?
答案 0 :(得分:3)
使用this.Height而不是this.Size.Height并使用textbox.Top而不是textbox.Location.Y。
答案 1 :(得分:0)
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);
}