2011-08-25 68 views
1

在我的代碼如下,當用戶右鍵單擊我的DataGridView中的一個單元格時,我顯示了一個上下文菜單。我也喜歡用戶右鍵單擊的單元格來更改背景顏色,以便他們可以看到他們「單擊右鍵選擇」的單元格。有沒有辦法給我的代碼添加一些東西,以便發生這種情況?突出顯示DataGridView中的選定單元格?

private void dataGridView2_MouseClick(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Right) 
     { 
      ContextMenu m = new ContextMenu(); 
      MenuItem mnuCopy = new MenuItem("Copy"); 
      mnuCopy.Click += new EventHandler(mnuCopy_Click); 
      m.MenuItems.Add(mnuCopy); 

      int currentMouseOverRow = dataGridView2.HitTest(e.X, e.Y).RowIndex;    

      m.Show(dataGridView2, new Point(e.X, e.Y)); 

     } 
    } 

回答

2

很顯然,你已經入侵了我的工作站,並且看到了我最近的一些工作。我誇大了一點,因爲我沒有做你想做的事情,只是稍微調整了我的能力。

我會修改您的MouseClick事件以獲得DGV的CurrentCell。一旦擁有它,請將CurrentCellStyle屬性與您想要的SelectionBackColor一起設置。事情是這樣的:

// ... 
DataGridView.HitTestInfo hti = dataGridView2.HitTest(e.X, e.Y); 
if (hti.Type == DataGridViewHitTestType.Cell) { 
    dataGridView2.CurrentCell = dataGridView2.Rows[hti.RowIndex].Cells[hti.ColumnIndex]; 
    dataGridView2.CurrentCell.Style = new DataGridViewCellStyle { SelectionBackColor = System.Drawing.Color.Yellow}; 
} 
//... 

以上是有點「空氣代號Y」(換句話說,我還沒有嘗試用你的代碼合併,並運行它),但我希望你的想法。請注意,我通過點擊測試檢查單元格是否被點擊;如果你不這樣做,並且用戶不點擊一個單元格,你可能會遇到一些問題。

現在有一個問題,此代碼將更改SelectionBackColor您右鍵單擊的所有單元格。這很容易在DGV的CellLeave來還原該屬性:

private void dgvBatches_CellLeave(object sender, DataGridViewCellEventArgs e) { 
    dataGridView2.CurrentCell.Style = new DataGridViewCellStyle { SelectionBackColor = System.Drawing.SystemColors.Highlight }; 
} 

我必須記住這樣的視覺影響;感謝您提出這個問題。

+0

對您的工作站進行黑客入侵很抱歉!哦,並且忽略辦公室裏隱藏的相機。另外,如果您收到來自NURV軟件的名爲加里溫斯頓的人的電話,請掛斷電話。謝謝!! – Kevin

相關問題