2017-04-24 72 views
0

介绍VB.NET绑定Datagridview - 动态改变字体?

我有了在我的代码早在分配一个DataTable给它填充它的数据一个DataGridView。数据显示没有问题。然后,我试图稍后通过并将背景颜色和字体应用于只有特定的单元格因此不是全部。

我从做一些研究,这似乎通过每个单元格的样式属性来完成这个尝试

现在。我建立了一个圈,像这样:

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 

该行不。似乎很奇怪,我可以将样式应用于列而不是连续。

+1

环通所有行 - 无论用户是否曾经滚动到他们 - 是低效。使用CellFormatting事件来评估条件并在那里设置适当的样式。 – Plutonix

+0

@Plutonix问题更多的是为什么“DataGridView1.Rows(row).Cells(col).Style = strikethrough_style”不起作用。我可以并且会在适当的条件下编写我的代码;然而,无论我是否循环或者通过我的条件,都会引用相同的代码,那么您如何建议我解决这个问题Plutonix? –

回答

0

所以我在尝试了很多事情并想分享之后找到了答案,所以没人会犯同样的错误。起初,我有我的风格的代码存在的我的datagridview绑定后右:

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 

的问题,这是在DataGridView时间太长,完成绑定数据。

更好的方法是做造型后的数据已通过绑定完整的事件势必:

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 
0
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 

它应该工作。

+0

请在我的问题中看到我的更新,但我尝试了你所说的并且仍然没有任何改变。 –