前30%显示DataGridView

时间:2016-06-07 14:48:36

标签: vb.net datagridview

首先:30%并不重要。这是一个设计问题。我们也可以说前3个显示列。

在我的DataGridView我使用BackgroundColors Rows向用户传递了一些信息。

要在选择行时向用户显示此信息,前30%的列应与SelectionBack/ForeColor获得相同的Back/ForeColor

到目前为止,使用

从未出现过问题
  • .cells(0).Style.SelectionBackColor = .cells(0).Style.Backcolor
  • (等等)。

现在我添加了允许用户重新排序Columns的函数,这使得以下Statement变为true:

  • ColumnIndex != DisplayedIndex

该声明为true,使得SelectionBackColor-Changed单元格在行中混合,而不再在第一列中混合。它仍然可以完成这项工作,但看起来很糟糕。

是否有像" DisplayedColumns"我可以用来调用前几个DisplayedColumns的.DisplayedIndex值的顺序收集?如果没有,我怎么能有效地创造一个属于我自己的呢?

编辑:

用户还可以隐藏与他无关的特定列。因此,我们必须了解Column.DisplayedIndexColumn.Visble

使用以下代码:

Try
 ' calculate what is thirty percent
 Dim colcount As Integer = oDic_TabToGridview(TabPage).DisplayedColumnCount(False)
 Dim thirtyPercent As Integer = ((colcount / 100) * 30)
 ' Recolor the first 30 % of the Columns
 Dim i As Integer = 0
 Dim lastCol As DataGridViewColumn = oDic_TabToGridview(TabPage).Columns.GetFirstColumn(DataGridViewElementStates.Visible)
 While i < thirtyPercent
   .Cells(lastCol.Index).Style.SelectionBackColor = oCol(row.Item("Color_ID") - 1)
   .Cells(lastCol.Index).Style.SelectionForeColor = Color.Black
   lastCol = oDic_TabToGridview(TabPage).Columns.GetNextColumn(lastCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
   i += 1
 End While
Catch ex As Exception
  MsgBox(ex.Message & vbNewLine & ex.StackTrace)
End Try

1 个答案:

答案 0 :(得分:1)

我们首先假设您按照以下方式对行进行着色:

Me.dataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.PowderBlue
Me.dataGridView1.Rows(1).DefaultCellStyle.BackColor = Color.Pink
' ...etc.

DataGridView.CellPainting事件处理程序中,您可以使用DataGridViewColumnCollection.GetFirstColumnDataGridViewColumnCollection.GetNextColumn方法确定绘制单元格是否属于第一个N列。

如果单元格属于这些列,请将单元格的SelectionBackColor设置为单元格的BackColor。否则将其设置为默认的突出显示颜色。

Dim column As DataGridViewColumn = Me.dataGridView1.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
e.CellStyle.SelectionBackColor = Color.FromName("Highlight")

' Example: Loop for the first N displayed columns, where here N = 2.
While column.DisplayIndex < 2
    If column.Index = e.ColumnIndex Then
        e.CellStyle.SelectionBackColor = e.CellStyle.BackColor
        Exit While
    End If

    column = Me.dataGridView1.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
End While

Example GIF reording columns but first 2 remain row colored

作为旁注:您可能需要考虑更改这些单元格上的ForeColor以提高可读性 - 具体取决于行的BackColor选项。同样,如果从这些第一列N列中仅选择一个单元格,则可能很难注意到。

相关问题