在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;
}
}
}