【发布时间】:2022-01-23 19:32:09
【问题描述】:
这是我在这里的第一个问题,所以请多多包涵。
目的:
我想要完成的是允许用户在 Windows 窗体应用程序中编辑 DataGridView(绑定到自定义类的对象列表)中的行。此外,当在 DataGridView 中生成新行时,我需要提供一些默认值,这是我使用 DataGridView 中的 DefaultValuesNeeded 事件处理程序实现的。
问题: 编辑行时,用户必须能够在 DataGridView 之外导航(例如,导航到 TextBox 以提供额外信息),但如果用户在编辑之前离开新行,默认值将从行中消失强>。这是我需要避免的。如果用户编辑新行的任何单元格,然后单击表单中的其他位置,则该行中的所有值都保留在那里,这是正确的,也是所需的行为。
我创建了一个小项目来说明这一点。 表格:
Imports System.ComponentModel
Public Class Form1
Private Sub dgvAsientos_DefaultValuesNeeded(sender As Object, e As Windows.Forms.DataGridViewRowEventArgs) Handles DataGridView1.DefaultValuesNeeded
e.Row.Cells("ID").Value = Me.DataGridView1.Rows.Count
e.Row.Cells("Name").Value = "Test Name " & Me.DataGridView1.Rows.Count
e.Row.Cells("Description").Value = "Description " & Me.TextBox1.Text & " " & Me.DataGridView1.Rows.Count
Me.DataGridView1.BindingContext(Me.DataGridView1.DataSource, Me.DataGridView1.DataMember).EndCurrentEdit()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myList As New BindingList(Of ExampleClass)
For n = 0 To 5
Dim itemn As New ExampleClass
itemn.ID = n
itemn.Name = "Name_" & n
itemn.Description = "Description_" & n
itemn.OptionalField = "OptionalField_" & n
myList.Add(itemn)
Next
Dim bs As New BindingSource()
bs.DataSource = myList
Me.DataGridView1.DataSource = bs
End Sub
End Class
示例类:
Public Class ExampleClass
Public Property ID As Integer
Public Property Name As String
Public Property Description As String
Public Property OptionalField As String
End Class
任何帮助将不胜感激。我发现关于 DefaultValuesNeeded + BindingSources + 用户关注其他控件时丢失的值的信息很少;其中一些让我在下一行添加了一行,但我没有发现这有什么不同。
(...).EndCurrentEdit()
我还找到了为绑定源添加新事件添加处理程序的建议,该事件返回一个具有我需要的默认值的对象实例,同样没有区别。
Private Sub myBindingSource_AddingNew(sender As Object, e As AddingNewEventArgs)
e.NewObject = CreateNewExample()
End Sub
我希望问题和格式是正确的。提前致谢, MBD
【问题讨论】:
标签: vb.net winforms datagridview bindingsource bindinglist