我正在尝试将use
的所有列值作为DataTable
放在面板中。
但问题是我继续拥有相同的循环。我根据CheckBox
限制了数组循环,但它仍在循环中。
Do note that there are tabs (they are sheets from an Excel file I've imported).
以下是我的问题的直观表示。
我想将其剪切到F19并结束循环。
Column.Count
答案 0 :(得分:2)
你只需要创建一次数组,你只需要迭代一次。
int dynamicHeight = 0;
int padding = 10;
CheckBox[] chk = new CheckBox[dt.Columns.Count];
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
var column = dt.Columns[i];
chk[i] = new CheckBox();
chk[i].Name = column.ColumnName;
chk[i].Text = column.ColumnName;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
panelCol.Controls.Add(chk[i]);
dynamicHeight += 20;
panelCol.Size = new Size(120, dynamicHeight);
panelCol.Controls.Add(chk[i]);
chk[i].Location = new Point(0, dynamicHeight);
chk[i].Size = new Size(120, 21);
panelCol.BackColor = Color.White;
panelCol.AutoScroll = true;
//panelCol.AutoScrollMinSize = new Size (0, 1200);
}
实际上,我认为你甚至不需要阵列,除非你以后用它做什么。您可以删除它,只需用chk[i]
替换checkBox
的每个实例。
答案 1 :(得分:0)
添加复选框的代码正在运行dt.Columns.Count * dt.Columns.Count
次,理想情况下,它应该只运行dt.Columns.Count
次以获得所需的输出。
在不改变实施代码的情况下,以下内容适用于您的情况。
CheckBox[] chk = new CheckBox[dt.Columns.Count];
for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
chk[i] = new CheckBox();
chk[i].Name = dt.Columns[i].ColumnName;
chk[i].Text = dt.Columns[i].ColumnName;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
panelCol.Controls.Add(chk[i]);
dynamicHeight += 20;
panelCol.Size = new Size(120, dynamicHeight);
panelCol.Controls.Add(chk[i]);
chk[i].Location = new Point(0, dynamicHeight);
chk[i].Size = new Size(120, 21);
panelCol.BackColor = Color.White;
panelCol.AutoScroll = true;
}
OR
int i = 0;
CheckBox[] chk = new CheckBox[dt.Columns.Count];
foreach (DataColumn column in dt.Columns)
{
chk[i] = new CheckBox();
chk[i].Name = column.ColumnName;
chk[i].Text = column.ColumnName;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
panelCol.Controls.Add(chk[i]);
dynamicHeight += 20;
panelCol.Size = new Size(120, dynamicHeight);
panelCol.Controls.Add(chk[i]);
chk[i].Location = new Point(0, dynamicHeight);
chk[i].Size = new Size(120, 21);
panelCol.BackColor = Color.White;
panelCol.AutoScroll = true;
i++;
//panelCol.AutoScrollMinSize = new Size (0, 1200);
}