這是我在這里的第一個問題,所以請對我仁慈。
目的:
我想要完成的是允許用戶從 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
uj5u.com熱心網友回復:
當用戶通過導航到最后一行然后在編輯單元格之前離開該行在 DataGridView 中添加新行時;在這種情況下,將取消添加行。這是因為某些內部邏輯會在行不臟時取消新行。
要改變這種行為,您可以處理RowValidating或RowLeave事件,然后通知當前單元格已臟,然后結束當前編輯。
C# 示例
private void dgv1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == dgv1.NewRowIndex)
{
dgv1.NotifyCurrentCellDirty(true);
dgv1.BindingContext[dgv1.DataSource, dgv1.DataMember].EndCurrentEdit();
dgv1.NotifyCurrentCellDirty(false);
}
}
VB.NET 示例
Private Sub dgv1_RowLeave(sender As Object, e As DataGridViewCellEventArgs) _
Handles dgv1.RowLeave
If e.RowIndex = dgv1.NewRowIndex Then
dgv1.NotifyCurrentCellDirty(True)
dgv1.BindingContext(dgv1.DataSource, dgv1.DataMember).EndCurrentEdit()
dgv1.NotifyCurrentCellDirty(False)
End If
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394763.html
標籤:网络 winforms 数据网格视图 绑定源 绑定列表
