Winform實現在Datagridview列首右鍵彈出隱藏列菜單

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.