查找特定行是否包含选定(突出显示)的单元格

时间:2015-05-06 07:01:16

标签: vb.net winforms select datagridview backcolor

目前,我已经创建了一个循环,该循环遍历我的datagridview中的每个单元格,以查找是否选择了任何单元格(突出显示),如果是,则单元格的行/列标题backcolor会发生变化。我遇到的问题是,一旦行数和列数开始变大,我就开始遇到滞后。所以我想知道是否有人能够立即找到行或列是否包含选定或突出显示的单元格而不使用循环。

我希望像我这样的东西.datagridview1.rows(1).selectedcells.count会存在,但是还没有找到类似的东西,那就行了。 另一个选项(我不想这样做)是在进行选择时为标题单元着色。

以下是我用来查找选择的内容。我只通过显示的单元格来循环以减少滞后(这是有效的),但是我需要将标题单元着色,即使选定的单元格不在视图中(然后它也不起作用)。

            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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

将此代码放在数据网格视图MouseDown事件中......

      function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                imgId = '#preview-'+$(input).attr('id');
                $(imgId).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
      }


      $("form#mainform input[type='file']").change(function(){
        readURL(this);
      });

有关更多信息,请使用how to highlight specific row in datagridview in c#

相关问题