Erik
Erik

Reputation: 95

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?

Upvotes: 1

Views: 2729

Answers (2)

ChrisF
ChrisF

Reputation: 137108

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;
    }
}

Upvotes: 3

TreDubZedd
TreDubZedd

Reputation: 2556

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

Upvotes: 0

Related Questions