VB2010。我已经研究过这个问题,似乎无法找到它的原因或解决方法。我所拥有的是绑定到DataTable的DataGridView。我允许用户选择编辑模式,该模式打开/关闭ReadOnly属性。一旦ReadMode = True,我确保将DataTable设置为AcceptChanges。设置此属性后,我的所有单元格格式都会消失。
我在表单加载时执行此操作:
Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
dgv.DataSource = Nothing
dgv.DataSource = GetTripData()
dgv.AutoResizeColumns()
dgv.ClearSelection()
dgv.ReadOnly = True
End Sub
然后用户可以单击菜单项进入编辑模式:
Private Sub mnuEditMode_Click(sender As System.Object, e As System.EventArgs) Handles mnuEditMode.Click
If mnuEditMode.Checked Then
dgv.ReadOnly = False
dgv.AllowUserToAddRows = True
dgv.AllowUserToDeleteRows = True
Else
dgv.ReadOnly = True
dgv.AllowUserToAddRows = False
dgv.AllowUserToDeleteRows = False
'accept all changes. if we dont do this any row that is deleted will still exist in the DataTable.
Dim dt As DataTable = CType(dgv.DataSource, DataTable)
If dt IsNot Nothing Then
dt.AcceptChanges() 'note: this causes custom cell font to be cleared
End If
End If
End Sub
一旦进入编辑模式,他们就可以决定要更改哪些细胞。他们列入要更改的两个单元格将被处理:
'update the proper cells via the DataGridView
dgv.Rows(2).Cells(5).Value = "HOME"
dgv.Rows(2).Cells(6).Value = 10
'bold the cell's font in the DataGridView
Dim styleUpdated As New DataGridViewCellStyle
styleUpdated.Font = New Font(dgv.Font, FontStyle.Bold)
dgv.Rows(2).Cells(6).Style = styleUpdated
dgv.Rows(2).Cells(6).Style = styleUpdated
'refresh the DGV
dgv.Refresh()
这个有效!我可以看到DGV的变化。现在他们完成了编辑数据,所以他们点击菜单项来设置编辑模式关闭,并设置dgv.ReadOnly = True,我也设置了dt.AcceptChanges。最后一个方法AcceptChanges清除修改过的单元格上的所有粗体字体。
这是预期的行为吗?如果是这样有什么建议可以保持我编辑的单元格格式化?
答案 0 :(得分:0)
这不是一个真正的答案,但我想发布一段重要的代码,所以我将其作为答案发布。我刚刚测试了下面的代码,它对我有用,因为大胆的文本在点击两个Buttons
时仍然存在。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim table As New DataTable
With table.Columns
.Add("Id", GetType(Integer))
.Add("Name", GetType(String))
.Add("Age", GetType(Integer))
End With
With table.Rows
.Add(1, "Mary", 20)
.Add(2, "Paul", 30)
.Add(3, "Peter", 40)
End With
DataGridView1.DataSource = table
Dim style = DataGridView1.Rows(1).Cells(1).Style
style.Font = New Font(DataGridView1.Font, FontStyle.Bold)
DataGridView1.Rows(1).Cells(1).Style = style
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With DataGridView1
.ReadOnly = True
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
End With
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
With DataGridView1
.ReadOnly = False
.AllowUserToAddRows = True
.AllowUserToDeleteRows = True
End With
End Sub
End Class
我建议您放弃该代码,如果它适合您,您就会知道原始项目中还有其他内容。然后,您可以缓慢地修改该测试项目,使其越来越像您现有的项目,然后您应该能够看到此功能的中断位置。