我正在使用datagridview将Access数据库填充到VB.net中的表单。我想在用户更改行中的值时执行某些操作(验证/更新数据库)。我想等到该行失去焦点以执行更改。我正在使用RowLeave事件来执行任务。问题是当加载datagridview的表单时,它会自动运行RowLeave事件。
如何进行表单加载而不运行RowLeave事件?是什么导致在加载表单时触发RowLeave事件?
编辑:这是我的代码的一部分:
Public Sub loadGradeForm(ByRef temp As Teacher)
currTeacher = temp
Me.showGrades() 'Populating the datagridview (GradeGridView)
Me.Show()
'After the form loads, it automatically goes to RowLeave when I go through debugging
End Sub
Private Sub showGrades()
GradeGridView.DataSource = Nothing
GradeGridView.Rows.Clear()
GradeGridView.Columns.Clear()
GradeGridView.AutoGenerateColumns = False
GradeGridView.AutoSize = True
GradeGridView.DataSource = currTeacher.ListOfClasses()
Dim column0 As DataGridViewColumn = New DataGridViewTextBoxColumn()
column0.DataPropertyName = "Class"
column0.Name = "Class"
GradeGridView.Columns.Add(column0)
Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
column.DataPropertyName = "Grade"
column.Name = "Grade"
GradeGridView.Columns.Add(column)
Dim column1 As DataGridViewColumn = New DataGridViewTextBoxColumn()
column1.DataPropertyName = "Semester"
column1.Name = "Semester"
GradeGridView.Columns.Add(column1)
End Sub
Private Sub GradeGridView_RowLeave(sender As Object, e As DataGridViewCellEventArgs) Handles GradeGridView.RowLeave
MsgBox(e.RowIndex)
'This is just a test to see if RowLeave is triggered
End Sub
答案 0 :(得分:1)
当您的DataGridView填充了行时,如果DataGridView失去焦点,则必须以编程方式保留行。
为了避免在表单将行加载到DataGridView时触发代码,我可以想到两个解决方案:
GradeGridView_RowLeave()
为Me.IsLoaded
的情况下执行True
- 方法中的逻辑。GradeGridView_RowLeave(sender As Object, e As DataGridViewCellEventArgs)
Handles GradeGridView.RowLeave
并添加一行{{1} } AddHandler GradeGridView.RowLeave, AddressOf GradeGridView_RowLeave
- 方法的底部。当然,只有在程序开始时只加载一次数据时,上述解决方案才有效。如果您需要再次加载数据,就像用户单击更新 -Button一样,我建议您在类中添加showGrades()
- 布尔标志,之前将设置为true加载发生,加载完成时为false。在执行LoadingMode
的逻辑之前,可以检查此布尔变量,类似于Me.IsLoaded
。