我可能没有使用正确的控件来实现我想要的。我正在用控件填充表格,我希望每列自动调整大小以适应其中包含的控件。例如,一列文本框将比一列复选框宽。由于不同操作系统、不同 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;
}*/
}
(是的,它需要大量重构——我只是想让它先工作)
注释掉的位会导致超出范围的异常,即使在逻辑上(对我而言)它不应该。该范围似乎仅限于我在设计时设置的任何内容,而不是在运行时。