Datagridview自定义行突出显示

时间:2014-04-28 14:58:46

标签: winforms datagridview

我有一个DataGridView(WinForms,C#)。我想做的就是在左/右部分划分网格。因此,当我单击左侧部分(3,3)时将突出显示,例如,当点击右侧部分(6,6)时将突出显示。

Col1 | Col2 | Col3 | Col4
-------------------------
 1      1       2     2
 3      3       4     4
 5      5       6     6

获取价值不是问题,但突出显示..?

    int iCol = dgv.CurrentCell.ColumnIndex;
    if (iCol == 0 || iCol == 1)   // left side
    { 

    }
    else  // right side
    {
    }

1 个答案:

答案 0 :(得分:0)

我希望这对你有所帮助,但你不应该直接在代码中编写列索引,我认为用数学表达式来控制索引是更好的解决方案。 此代码对于大数据也会很慢,因此您可以使用列选择。但是,如果使用列选择,则会在单击列标题时阻止重新排序行。

  Private Sub DataGridView1_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    DataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect
    If e.ColumnIndex < DataGridView1.ColumnCount / 2 Then
        For Each c As DataGridViewColumn In DataGridView1.Columns
            If c.Index < DataGridView1.ColumnCount / 2 Then
                For Each r As DataGridViewRow In DataGridView1.Rows
                    r.Cells(c.Index).Style.BackColor = Color.Blue
                Next
            Else
                For Each r As DataGridViewRow In DataGridView1.Rows
                    r.Cells(c.Index).Style.BackColor = Color.Gray
                Next
            End If
        Next
    Else
        For Each c As DataGridViewColumn In DataGridView1.Columns
            If c.Index >= DataGridView1.ColumnCount / 2 Then
                For Each r As DataGridViewRow In DataGridView1.Rows
                    r.Cells(c.Index).Style.BackColor = Color.Blue
                Next
            Else
                For Each r As DataGridViewRow In DataGridView1.Rows
                    r.Cells(c.Index).Style.BackColor = Color.Gray
                Next
            End If
        Next
    End If
End Sub