【问题标题】:Add a navigation button for a DataGridView为 DataGridView 添加导航按钮
【发布时间】:2020-01-06 17:43:14
【问题描述】:

我正在为一个简单的 CRM 系统编写代码,该系统包含一个带有 DataGridView 和一些文本字段的表单。代码是用VB.net编写的。

DataGridView 链接到 BindingSource,文本字段连接到 DataGridView 并通过选择 DataGridViewRow 进行填充,效果很好。

代码:

Form1.CRM01Form2MainID.Text = Form1.DataGridView1.Rows(Form1.DataGridView1.CurrentRow.Index).Cells(1).Value

我想添加导航按钮(用于上下导航),出于特定原因,我不想使用 BindingNavigator。

我使用下面的代码来选择下一行:

rowidScroll = DataGridView1.CurrentRow.Index (dim is public)
DataGridView1.Rows(rowidScroll + 1).Selected = True

问题是所选行确实会向下移动一个位置,但 DataGridView1.CurrentRow.Index 没有更新 1。因此导航在一步后停止并且文本字段没有更新。

如果有人能解释如何解决这个问题,我们将不胜感激。

【问题讨论】:

    标签: vb.net datagridview bindingsource


    【解决方案1】:

    您根本不应该在代码中使用网格。您应该完全按照BindingNavigator 所做的那样做,即使用BindingSourceBindingNavigator 只是 BindingSource 的 UI,特别是 MoveFirstMovePreviousPositionCountMoveNextMoveLast 成员。如果您想创建自己的 UI,那么您可以为相同的成员创建,或者至少为您想要公开的成员创建。例如,如果您只想按记录向前和向后移动,那么您只需要调用 MovePreviousMoveNext 方法:

    Private Sub movePreviousButton_Click(sender As Object, e As EventArgs) Handles movePreviousButton.Click
        myBindingSource.MovePrevious()
    End Sub
    
    Private Sub moveNextButton_Click(sender As Object, e As EventArgs) Handles moveNextButton.Click
        myBindingSource.MoveNext()
    End Sub
    

    我不是 100% 确定,但我认为如果没有上一个或下一个记录可以移动,这些方法将根本不起作用,但你应该测试一下。无论哪种方式,如果 Button 不能做任何有用的事情,最好禁用它:

    Private Sub movePreviousButton_Click(sender As Object, e As EventArgs) Handles movePreviousButton.Click
        myBindingSource.MovePrevious()
        SetNavigationButtonStates()
    End Sub
    
    Private Sub moveNextButton_Click(sender As Object, e As EventArgs) Handles moveNextButton.Click
        myBindingSource.MoveNext()
        SetNavigationButtonStates()
    End Sub
    
    Private Sub SetNavigationButtonStates()
        movePreviousButton.Enabled = (myBindingSource.Position > 0)
        moveNextButton.Enabled = (myBindingSource.Position < myBindingSource.Count - 1)
    End Sub
    

    您也不应该在网格和其他控件之间手动移动数据。您也应该绑定到这些控件,例如

    myBindingSource.DataSource = myDataTable
    myDataGridView.DataSource = myBindingSource
    myTextBox.DataBindings.Add("Text", myBindingSource, "SomeColumn")
    

    然后您的TextBox 将自动显示当前行中的SomeColumn 值。通过TextBox 完成的任何编辑也将自动推送到数据源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-29
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      相关资源
      最近更新 更多