通过一个CheckedListBox实现,在CheckedListBox选中想要显示的列即可,代码如下:
private void Form1_Load(object sender, EventArgs e)
{
SBKHSBYQ(dataGridView1, checkedListBox1);
}
public static void SBKHSBYQ(DataGridView D, CheckedListBox C)
{
Dictionary<string, string> temps = new Dictionary<string, string>();
foreach (DataGridViewColumn item in D.Columns)
{
C.Items.Add(item.HeaderText);
temps[item.HeaderText] = item.Name;
C.SetItemChecked(item.Index, item.Visible);
}
C.ItemCheck += (o, e) =>
{
if(e.NewValue==CheckState.Unchecked)
D.Columns[temps[(o as CheckedListBox).SelectedItem.ToString()]].Visible=false;
else if(e.NewValue==CheckState.Checked)
D.Columns[temps[(o as CheckedListBox).SelectedItem.ToString()]].Visible = true;
};
}
网友评论