1

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?

2 Answers 2

3

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;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I want to controll which coulmns to get displayed when the application is running. I want to right klick at the top of the gridview and choose wich columns to display from a list. There got to be a way to that.
I will try run it later. Thnx very much :D
I cant get this working :S, I get errors with the foreach loop and I dont get eny menus on the form when I run the application :S
@Erik - what errors do you get? I did extract the code from my application so there's a chance I missed something. You'll have to bind the right click to the context menu as well - which I haven't shown.
If I copy and paste your code into my application it dose not work, first I must create an instanse of ContextMenu context = new ContextMenu(), then in the foreach loop the error is: The object dose not contain a definition for Name and Visible. What do I have to do? Iam little bit confused :D
|
0

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

1 Comment

I was wondering if there is eny way to choose the coulumns when I run the application. I whant to right klick at the top of the gridview and choose the coulmns I want from a list. Is there any way to that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.