在Winform中右键弹出Datagridview显示列菜单已经有很多人做了,参看下面链接.

http://www.codeproject.com/KB/grid/DGVColumnSelector.aspx

源码链接http://www.codeproject.com/KB/grid/DGVColumnSelector/DataGridViewColumnSelector_src.zip

但当你的有很多很多列或你对你的列名们不是太熟悉就有些麻烦了,把要显示的列勾选出来是一件很头疼的事.

下面提出直接隐藏当前列的办法,以抛砖引玉.

首先在FORM中添加一个Datagridview,一个ContextMenuStrip,给ContextMenuStrip加一个显示名为(隐藏)的ToolStripMenuItem

代码很简单,加了个变量TempColIndex存储当前列的索引,我就不做注释了.

 

Public Class Form1
Dim TempColIndex As Int16 = -2
Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
If e.RowIndex < 0 Then
TempColIndex
= e.ColumnIndex
ContextMenuStrip1.Show(MousePosition.X, MousePosition.Y)

End If
End If

End Sub

Private Sub 隐藏ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 隐藏ToolStripMenuItem.Click
If TempColIndex >= 0 Then
DataGridView1.Columns(TempColIndex).Visible
= False
End If
End Sub
End Class

 

public class Form1
{
Int16 TempColIndex
= -1;

private void DataGridView1_CellMouseDown(object sender, System.Windows.Forms.DataGridViewCellMouseEventArgs e)
{
if (e.Button == Windows.Forms.MouseButtons.Right) {
if (e.RowIndex < 0) {
TempColIndex
= e.ColumnIndex;

ContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}

}
}

private void 隐藏ToolStripMenuItem_Click(System.Object sender, System.EventArgs e)
{
if (TempColIndex >= 0) {
DataGridView1.Columns(TempColIndex).Visible
= false;
}
}
}

 

posted on 2010-05-30 18:12  YuanLH  阅读(1856)  评论(0编辑  收藏  举报