Introduction
我有一个datagridview,它通过在代码的早期为datatable分配数据来填充其数据。数据显示没有问题。然后,我试图在以后的过程中,将背景色和字体应用到,只适用于某些单元格,,所以不是所有的单元格。
我已经尝试过的
现在,通过做一些研究,这似乎是通过每个单元格的样式属性来完成的。我建立了一个类似这样的循环:
Dim strikethrough_style As New DataGridViewCellStyle
strikethrough_style.Font = strikethrough_font
strikethrough_style.BackColor = Color.Red
For row = 0 To DataGridView1.Rows.Count - 1
For col = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Rows(row).Cells(col).Style = strikethrough_style
Next
Next这应该会改变我所有的细胞,使其有一个红色的背景,并有一个划线字体,但是在运行时,所有的单元格都不会改变。
我可以像这样更改defaultcellstyle样式属性:
DataGridView1.DefaultCellStyle = strikethrough_style对所有细胞都有效,
但正如我前面所说,我希望最终只更改某些行,而不是所有行。有什么东西压倒了我的风格吗?如果是的话,我怎么才能绕开这件事?
更新
奇怪的是,如果我试着:
DataGridView1.Columns(4).DefaultCellStyle = strikethrough_style该列确实应用了样式;但是,当我尝试:
DataGridView1.Rows(1).DefaultCellStyle = strikethrough_style这一排没有。奇怪的是,我可以将样式应用于列,而不是行。
发布于 2017-04-25 14:03:59
所以我在尝试了很多事情之后找到了答案,并且想和大家分享,所以没有人会犯和我一样的错误。最初,我的样式代码是在数据视图绑定之后出现的:
DataGridView1.DataSource = sql_server.execute_sql(sql_server_location, commands)
Dim strikethrough_style As New DataGridViewCellStyle
strikethrough_style.Font = New Font(DataGridView1.Font.Name, DataGridView1.Font.Size, FontStyle.Strikeout)
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(1).Value = True Then
row.DefaultCellStyle = strikethrough_style
End If
Next这方面的问题是数据视图要花太长时间才能完成数据绑定.
更好的方法是在通过绑定完整事件绑定数据之后执行样式设置:
Private Sub dataGridView1_DataBindingComplete(ByVal sender As Object, ByVal e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
Dim strikethrough_style As New DataGridViewCellStyle
strikethrough_style.Font = New Font(DataGridView1.Font.Name, DataGridView1.Font.Size, FontStyle.Strikeout)
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(1).Value = True Then
row.DefaultCellStyle = strikethrough_style
End If
Next
End Sub发布于 2017-04-25 06:32:12
Dim strikethrough_style As New DataGridViewCellStyle
strikethrough_style.Font = New Font("Times New Roman", 16, FontStyle.Bold)
strikethrough_style.BackColor = Color.Red
For Each row As DataGridViewRow In Datagridview1.Rows
For i = 0 To Datagridview1.Columns.Count - 1
row.Cells(i).Style = strikethrough_style
Next
Next应该管用的。
https://stackoverflow.com/questions/43596386
复制相似问题