【问题标题】:Binding Source changes current item when datagrid looses focus当数据网格失去焦点时,绑定源更改当前项目
【发布时间】:2012-11-29 15:36:15
【问题描述】:

我在 VB.Net 2010 中有一个带有 6 个 DataGridViews 的 WinForm,每个都有自己的绑定源。我有一个额外的主 DataGridView 来控制其他网格中的内容。这是唯一允许添加新记录的网格。所有其他都以编程方式控制。主网格绑定源绑定到一个可观察的对象集合,并为该集合中的一个类对象附加一个绑定源。

我的问题是,当我单击主网格中的新行时,一切都会通过实例化一个新的单个类对象来清除,但是当我从网格中跳出或单击或其他任何东西时,绑定网格的源将其当前项重置为网格中的第一项。如果我将单个对象绑定源设置为新的实例化对象,它也会清除集合中的第一项。这不会发生在我们使用绑定到可观察集合的 DataGridView 的任何其他屏幕上。我错过了什么?

网格点击实现示例代码

Private Sub dgvReports_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvReports.CellClick
If e.RowIndex < 0 Or dgvReports.SelectedRows.Count < 0 Then
    Exit Sub
End If

If Not dgvReports.Rows(e.RowIndex).IsNewRow Then
    objReport = dgvReports.Rows(e.RowIndex).DataBoundItem
    objReport.SerializeToDB()
    intSelIndex = e.RowIndex
    objReport = objReport.Deserialize()
    If objReport.MsgObject.ErrMsg > "" Then
        objReport.MsgObject.DisplayErrMsg()
    End If
    btnDelete.Enabled = True And Not blnReadOnly
Else
    objReport = New RBL.Report
    objReport.GlobalID = Guid.NewGuid.ToString
    intSelIndex = e.RowIndex
    btnDelete.Enabled = False
End If
' The following 3 lines of code causes the first record in grid to be reset
' but works in other implementations    
'If objReport IsNot Nothing Then
    'bsReport.DataSource = objReport
'End If

btnApply.Enabled = False
UpdateReportObjects()
End Sub

Private Sub UpdateReportObjects()
Dim objRprt As RBL.Report = Nothing

If dgvReports.SelectedRows.Count = 1 Then
    objRprt = dgvReports.SelectedRows(0).DataBoundItem
End If

' Set all local observable collections to Report properties
If objReport.GlobalID = objRprt.GlobalID Then
    RptFieldLst = objReport.ReportFields
    RptTableLst = objReport.TableList
    DisplayFieldLst = objReport.DisplayFields
    SortFldLst = objReport.SortList
Else
' Instantiate new collections and set to new Report object properties
    RptTableLst = New RBL.ReportTables()
    RptFieldLst = New RBL.ReportFields()
    DisplayFieldLst = New RBL.ReportFields()
    NonDisplayFieldLst = New RBL.ReportFields()
    SortFldLst = New RBL.ReportSortOrders()
    objReport.TableList = RptTableLst
    objReport.ReportFields = RptFieldLst
    objReport.DisplayFields = DisplayFieldLst
    objReport.SortList = SortFldLst
End If
End Sub

【问题讨论】:

  • 你有代码要显示吗?似乎您在“休假活动”中具有某种自定义功能。
  • 代码中没有失去焦点或离开事件。我真的不能发布实际代码,因为它是专有的。我也许可以假装一些。
  • 您有任何“选择更改事件”吗?如果我没记错的话,我相信当重新绘制 dgv 时,它会选择第一个对象,直到找到在重新绘制之前选择的行。
  • 我目前没有使用 selection changed 事件,尽管我们的团队一直在讨论将我们所有的 cellclick 事件移动到 selection changed 事件中,以便我们处理箭头键和鼠标单击的行更改。

标签: vb.net winforms data-binding datagridview observablecollection


【解决方案1】:

问题被发现了,和往常一样,手指又指向了我自己。可观察集合的绑定源和单个项目的绑定源的 DataSource 设置为相同的变量对象,即单个类对象。 问题解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多