我可能没有使用正确的控件来实现我的需求。我正在用控件填充一个表格,并希望每一列根据其中包含的控件自动调整大小。例如,文本框列将比复选框列宽。我不想通过测量来解决问题,因为涉及到不同操作系统、不同DPI、不同字体等复杂性。表格可以水平扩展以适应控件,并带有滚动条。如何在TableLayoutPanel或其他控件中实现这一点?
谢谢。
编辑以添加代码:
private void UpdateLocations()
{
tableLayoutPanel1.RowCount = CurrentSchedule.location.Length + 1;
tableLayoutPanel1.ColumnCount = 7;
int row = 1;
int timeWidth = TextRenderer.MeasureText("00:00:00x", tableLayoutPanel1.Font).Width;
Label lab = new Label();
lab.Text = "Location";
tableLayoutPanel1.Controls.Add(lab, 0, 0);
lab = new Label();
lab.Text = "Arrive";
tableLayoutPanel1.Controls.Add(lab, 1, 0);
lab = new Label();
lab.Text = "Depart";
tableLayoutPanel1.Controls.Add(lab, 2, 0);
lab = new Label();
lab.Text = "Pass?";
tableLayoutPanel1.Controls.Add(lab, 3, 0);
lab = new Label();
lab.Text = "Path";
tableLayoutPanel1.Controls.Add(lab, 4, 0);
lab = new Label();
lab.Text = "Plat";
tableLayoutPanel1.Controls.Add(lab, 5, 0);
lab = new Label();
lab.Text = "Line";
tableLayoutPanel1.Controls.Add(lab, 6, 0);
foreach (location loc in CurrentSchedule.location)
{
TextBox tb = new TextBox();
tb.Text = loc.locationID;
tableLayoutPanel1.Controls.Add(tb, 0, row);
tb = new TextBox();
tb.Text = loc.arrivalTime;
tb.Width = timeWidth;
tableLayoutPanel1.Controls.Add(tb, 1, row);
tb = new TextBox();
tb.Text = loc.departureTime;
tb.Width = timeWidth;
tableLayoutPanel1.Controls.Add(tb, 2, row);
CheckBox cb = new CheckBox();
cb.Checked = loc.passingTime;
tableLayoutPanel1.Controls.Add(cb, 3, row);
tb = new TextBox();
tb.Text = loc.pathCode;
tableLayoutPanel1.Controls.Add(tb, 4, row);
tb = new TextBox();
tb.Text = loc.platformCode;
tableLayoutPanel1.Controls.Add(tb, 5, row);
tb = new TextBox();
tb.Text = loc.lineCode;
tableLayoutPanel1.Controls.Add(tb, 6, row);
row++;
}
/*for (int idx = 0; idx < tableLayoutPanel1.RowCount; idx++)
{
tableLayoutPanel1.RowStyles[idx].SizeType = SizeType.AutoSize;
}
for (int idx = 0; idx < tableLayoutPanel1.ColumnCount; idx++)
{
tableLayoutPanel1.ColumnStyles[idx].SizeType = SizeType.AutoSize;
}*/
}
(是的,它需要进行大量的重构 - 我只是试图先让它能正常工作)
尽管在逻辑上(对我来说)不应该出现数组越界异常,但被注释掉的部分确实会导致此问题。范围似乎被限制为设计时设置的内容,而非运行时。