下面的代码有效
void selectColumns_Click(object s, EventArgs e)
{
ListBox lBx = getListBox();
for (int i = 0; i < lBx.Items.Count-1;i++ )
{
bool contained = lBx.SelectedItems.Contains(lBx.Items[i]);
dgView.Columns[lBx.Items[i].ToString()].Visible = contained;
}
}
但这不起作用-抛出错误 “此枚举器绑定到的列表已被修改。仅当列表未更改时才能使用枚举器。”
void selectColumns_Click(object s, EventArgs e)
{
ListBox lBx = getListBox();
foreach (var item in lBx.Items )
{
bool cont = lBx.SelectedItems.Contains(item);
dgView.Columns[item.toString()].Visible = cont;
}
}
获取 ListBox 方法如下:
ListBox getListBox()
{
return columnsForm.Controls.OfType<ListBox>().First() as ListBox;
}
还通过单击 hideColumnsButton 填充列表框
void hideBtn_Click(object sender, EventArgs e)
{
getListBox().Items.Clear();
foreach(DataGridViewColumn col in dgView.Columns)
{
getListBox().Items.Add(col.Name);
}
columnsForm.ShowDialog();
}