简体   繁体   中英

C# - Datagridview columns

I have a DataGridView in a WinForm. I fill the DataGridView from a database table. I was wondering if there is any way to program my DataGridView so that I can choose which columns I want the gridview to show at runtime?

The simple answer is "yes".

In the first instance you need to set the AutoGenerateColumns property of the DataGridView to false then you can control which columns get displayed.

In the past I've created a context menu for the DGV:

ContextMenu = new ContextMenu();
foreach (var column in this.dataGridView.Columns)
{
    this.AddContextMenuItem(ContextMenu, column.Name, column.Visible);
}

private void AddContextMenuItem(ContextMenu contextMenu,
                                string columnName,
                                bool visible)
{
    var menuItem = new MenuItem(columnName,
        new EventHandler(this.ContextMenu_onClick)) { Checked = visible };
    contextMenu.MenuItems.Add(menuItem);
}

Then when the the menu option is toggled change the Visible property of the column.

private void ContextMenu_onClick(object sender, EventArgs e)
{
    var clicked = sender as MenuItem;
    if (clicked != null)
    {
        // Update the state of the context menu
        clicked.Checked = !clicked.Checked;

        // Update the visibity of this column
        this.dataGridView.Columns[clicked.Text].Visible = clicked.Checked;
    }
}

Use the DataGridView.AutoGenerateColumns property--set to false . Explicitly configure the columns you want, and you're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM