DataGridView columns visibility configuration window
This code allows you to change visibility of columns of any DataGridView component at program runtime. It shows simple window filled with list of columns of DataGridView. You can check columns on the list you want to be visible. Use this code with my other DataGridView extension methods http://extensionmethod.net/csharp/datagridview/load-save-configuration.
Source
using System.Windows.Forms;
namespace DataGridViewExtensions
{
public static class DataGridViewExtensions
{
public static void ShowConfigurationWindow(this DataGridView dataGridView)
{
using (var frmConfig = new FrmColumnsConfig(dataGridView))
{
frmConfig.ShowDialog();
}
}
}
public class FrmColumnsConfig : Form
{
private DataGridView _dataGridView;
public FrmColumnsConfig(DataGridView dataGridView)
{
InitializeComponent();
_dataGridView = dataGridView;
}
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
for (int i = 0; i < _dataGridView.Columns.Count; i++)
{
lstColumns.Items.Add(_dataGridView.Columns[i].HeaderText, _dataGridView.Columns[i].Visible);
}
}
private void lstColumns_ItemCheck(object sender, ItemCheckEventArgs e)
{
_dataGridView.Columns[e.Index].Visible = e.NewValue == CheckState.Checked;
}
private System.Windows.Forms.CheckedListBox lstColumns;
private System.ComponentModel.IContainer components = null;
private void InitializeComponent()
{
this.lstColumns = new System.Windows.Forms.CheckedListBox();
this.SuspendLayout();
this.lstColumns.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstColumns.FormattingEnabled = true;
this.lstColumns.Location = new System.Drawing.Point(0, 0);
this.lstColumns.Name = "lstColumns";
this.lstColumns.Size = new System.Drawing.Size(258, 214);
this.lstColumns.TabIndex = 0;
this.lstColumns.CheckOnClick = true;
this.lstColumns.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lstColumns_ItemCheck);
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(258, 214);
this.Controls.Add(this.lstColumns);
this.Name = "FrmColumnsConfig";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Columns configuration";
this.ResumeLayout(false);
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
}
}
Example
dgvInstance.ShowConfigurationWindow();
Author: Marcin Kozub
Submitted on: 23 jul. 2013
Language: C#
Type: System.Windows.Forms.DataGridView
Views: 5942