2015-05-06 65 views
0

目前,我創建了一個循環,遍歷我的datagridview中的每個單元格,以查找是否選擇了任何單元格(突出顯示),如果是,則該單元格的行/列標題背景更改。我遇到的問題是,一旦行數和列數開始變大,我開始經歷滯後。所以我想知道有沒有人知道立即能夠找到一行或一列是否包含選定或突出顯示的單元而不使用循環的方式。查找特定行是否包含選定(突出顯示)的單元格

我一直希望像me.datagridview1.rows(1).selectedcells.count這樣的東西存在,但一直沒有找到像那樣的東西,工作。 另一種選擇(我不喜歡這樣做)是在選擇時爲標題單元着色。

這是我用來找到選擇。我只通過循環顯示的單元格來減少滯後(其工作原理),但即使當選定的單元格不在視圖中時(不起作用),我也需要使用headercells着色。

  a = .FirstDisplayedCell.RowIndex 
     Do While a < .FirstDisplayedCell.RowIndex + .DisplayedRowCount(True) 
      b = .FirstDisplayedCell.ColumnIndex 
      Do While b < .FirstDisplayedCell.ColumnIndex + .DisplayedColumnCount(True) 
       If .Rows(a).Cells(b).Selected = False Then 
        .Rows(a).HeaderCell.Style.BackColor = colorfieldheader 
        .Columns(b).HeaderCell.Style.BackColor = colorfieldheader 
       End If 
       b += 1 
      Loop 
      a += 1 
     Loop 

     a = .FirstDisplayedCell.RowIndex 
     Do While a < .FirstDisplayedCell.RowIndex + .DisplayedRowCount(True) 
      b = .FirstDisplayedCell.ColumnIndex 
      Do While b < .FirstDisplayedCell.ColumnIndex + .DisplayedColumnCount(True) 
       If .Rows(a).Cells(b).Selected = True Then 
        .Rows(a).HeaderCell.Style.BackColor = colorfieldheaderhighlight 
        .Columns(b).HeaderCell.Style.BackColor = colorfieldheaderhighlight 
       End If 
       b += 1 
      Loop 
      a += 1 
     Loop 
+0

試試這個問題http://stackoverflow.com/ questions/8921848/how-to-get-rows-collection-based-on-selected-cells-in-datagridview這是C#,但前提是一樣的。 – DeanOC

+0

也許循環[DataGridView.SelectedCells](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells(v = vs.110).aspx),然後檢索單元格列屬性? –

+0

謝謝Dean,我現在正在查看您的鏈接。同時也感謝Justin,我使用了selectecells,但我不記得我爲什麼離開它,我會重新審視,看看我能否得到這個工作。 – Jarron

回答

0

你可以做這樣的事情C#代碼:

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
     { 
      foreach (DataGridViewCell cell in dataGridView1.SelectedCells) 
      { 

        dataGridView1.Rows[cell.RowIndex].DefaultCellStyle.BackColor = Color.Red; 

      } 
     } 

確保事件處理程序後,數據綁定連接。

如果您要突出顯示與選定單元格相同的行(藍色),則可能需要將SelectionMode設置爲FullRowSelect,即DataGridView。就像這樣:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
0

將此代碼放在您的數據網格視圖MouseDown事件......

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; 
      } 
     } 

,並獲取更多信息使用how to highlight specific row in datagridview in c#

相關問題