Automatically Adding DataGridView Columns

I have a DataGridView populated with product information. There are only 50 columns in a datagridview, but users do not always need all the columns, I want to help them choose which columns to show and which ones not to show.

One solution that I would like to program is that when the user right-clicks on the columns, they can choose from the list that appears and choose which columns to show and which not to do. Like the image below. enter image description here

How can i do this. I would really appreciate any help.

+5
source share
1 answer

, WinForms ContextMenuStrip Visible DataGridView.

, , :

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            BindingList<User> users = new BindingList<User>{
                  new User{Name = "John", Address="Home Street", Title="Mr."},
                  new User{Name = "Sally", Address="Home Street", Title="Mrs."}
            };

            contextMenuStrip1.AutoClose = true;       
            contextMenuStrip1.Closing += new ToolStripDropDownClosingEventHandler(contextMenuStrip1_Closing);

            dataGridView1.DataSource = users;

            dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
        }

        void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

            foreach (DataGridViewColumn gridViewColumn in this.dataGridView1.Columns)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Name = gridViewColumn.Name;
                item.Text = gridViewColumn.Name;
                item.Checked = true;
                item.CheckOnClick = true;
                item.CheckedChanged += new EventHandler(item_CheckedChanged);
                contextMenuStrip1.Items.Add(item);
            }

            foreach (DataGridViewColumn gridViewColumn in this.dataGridView1.Columns)
            {
                gridViewColumn.HeaderCell.ContextMenuStrip = contextMenuStrip1;
            }

        }

        void item_CheckedChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;

            if (item != null)
            {
                dataGridView1.Columns[item.Name].Visible = item.Checked;
            }
        }

        void contextMenuStrip1_Closing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
            {
                e.Cancel = true;
            }
        }
    }

    public class User
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Title { get; set; }
    }

}

User - , -, DataGridView .

, ( , ). , - , , ( ) .

, , DataGridView.

+1

All Articles