guangtoujiabaoji
V2EX  ›  问与答

winform 实现客户要求的在 DataGridView 自定义选择显示的列

  •  
  •   guangtoujiabaoji · Sep 21, 2018 · 1308 views
    This topic created in 2831 days ago, the information mentioned may be changed or developed.

    通过一个 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;
        };
    }
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3029 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:23 · PVG 08:23 · LAX 17:23 · JFK 20:23
    ♥ Do have faith in what you're doing.