65.9K
CodeProject 正在变化。 阅读更多。
Home

DataGridView 列显示/隐藏弹出窗口

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.81/5 (56投票s)

2008年12月23日

CPOL

1分钟阅读

viewsIcon

208454

downloadIcon

9033

一个为 DataGridView 添加列显示/隐藏功能的类

引言

许多应用程序都为用户提供了一个有用的功能,即显示/隐藏数据列。在 Windows Forms 中,用于显示表格数据的控件是 DataGridView,但它没有内置的列选择机制。我编写了一个名为 DataGridViewColumnSelector 的小类来填补这个空白。

背景

DataGridViewColumnSelector 类是一个新类,而不是 DataGridView 类的派生类。您不需要更改 DataGridView 实例的声明。只需创建一个 DataGridViewColumnSelector 实例,并将一个 DataGridView 实例附加到它。当用户右键单击单元格原点时,将显示一个弹出窗口,允许您选中/取消选中要显示的列。

列列表是通过 CheckedListBox 实现的,弹出效果是通过 ToolStripDropDown 对象实现的,该对象添加了一个 ToolStripControlHost 对象。后者包含 CheckedListBox。阅读文章 “如何:使用 ToolStripControlHost 包装 Windows Forms 控件”,以了解一些背景知识。

这是构造函数代码

// The constructor creates an instance of CheckedListBox and ToolStripDropDown.
// the CheckedListBox is hosted by ToolStripControlHost, which in turn is
// added to ToolStripDropDown.
public DataGridViewColumnSelector() {
	mCheckedListBox = new CheckedListBox();
	mCheckedListBox.CheckOnClick = true;
	mCheckedListBox.ItemCheck += 
		new ItemCheckEventHandler(mCheckedListBox_ItemCheck);

	ToolStripControlHost mControlHost = new ToolStripControlHost(mCheckedListBox);
	mControlHost.Padding = Padding.Empty;
	mControlHost.Margin = Padding.Empty;
	mControlHost.AutoSize = false;

	mPopup = new ToolStripDropDown();
	mPopup.Padding = Padding.Empty;
	mPopup.Items.Add(mControlHost);
}

当用户右键单击单元格原点时,将调用 mDataGridView_CellMouseClick。它清除并用列标题文本填充 CheckedListBox。然后它显示弹出窗口。这样,CheckedListBox 项目始终会刷新,以反映 DataGridView 列中发生的更改(列添加或名称更改等)。

void mDataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
	if (e.Button == MouseButtons.Right && e.RowIndex==-1 && e.ColumnIndex==-1) {
		mCheckedListBox.Items.Clear();
		foreach (DataGridViewColumn c in mDataGridView.Columns){
			mCheckedListBox.Items.Add(c.HeaderText, c.Visible);
		}
		int PreferredHeight = (mCheckedListBox.Items.Count * 16) + 7;
		mCheckedListBox.Height = (PreferredHeight < MaxHeight) ? 
					PreferredHeight : MaxHeight;
		mCheckedListBox.Width = this.Width;
		mPopup.Show(mDataGridView.PointToScreen(new Point (e.X,e.Y)));
	}
}

最后,当用户选中/取消选中 checkbox 时,相关的列可见性将通过 mCheckedListBox_ItemCheck 事件处理程序切换。

void mCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e){
	mDataGridView.Columns[e.Index].Visible = (e.NewValue == CheckState.Checked);
}

Using the Code

DataGridViewColumnSelector.cs 文件复制到您的项目中。如果需要,请更改命名空间。

您可以将 DataGridView 实例直接作为构造函数参数传递

new DataGridViewColumnSelector(dataGridView1);

或者,您可以创建一个实例,然后使用 DataGridView 属性附加一个 DataGridView

DataGridViewColumnSelector cs = new DataGridViewColumnSelector();
cs.DataGridView = dataGridView1;
cs.MaxHeight = 200;
cs.Width = 110;

可选地使用 MaxHeightWidth 属性来调整弹出窗口的大小。

历史

  • 2008 年 12 月 23 日:初始发布
© . All rights reserved.