2015-05-06 64 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#

相关问题