2016-06-07 94 views
1

首先:30%无关紧要。这是一个设计问题。我们也可以说前3个显示列。首先在DataGridView中显示30%的列

在我的DataGridView我使用BackgroundColorsRows来传递用户的一些信息。

为了让用户在选择行的同时可以看到此信息,前30%的列应与Back/ForeColor获得相同的SelectionBack/ForeColor

到目前为止从未被使用

  • .cells(0).Style.SelectionBackColor = .cells(0).Style.Backcolor
  • (等)的问题。

现在,我补充说,允许用户重新排序,这使得下面的语句成为真正的栏功能:

  • ColumnIndex != DisplayedIndex

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

是否有像“DisplayedColumns”集合的顺序的.DisplayedIndex值,我可以用它来调用第一个DisplayedColumns?如果没有,我怎么能有效地创造一个我自己的?


编辑:

用户也可以隐藏特定的列,不为他无所谓。因此,我们必须要注意的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

让我们先假定你是着色你行不知何故类似方式如下:

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

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

如果单元格属于一个这些列,请将单元格的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选择。同样,如果只从第一个列中选择一个单元格,则很难注意到这一点。

+0

几乎是最好的答案我曾经在这个平台上!帮助我的关键字是'DataGridView.Columns.GetNextColumn(...)'。我不知道这个功能,但我相信这对未来的项目非常有帮助。谢谢! – Luke

+0

很高兴帮助!我发现研究很有趣。 – OhBeWise