datatable.Rows.Find不起作用

时间:2012-03-01 14:49:40

标签: .net vb.net datatable

        Dim datatable_default_view As DataTable = _datatable.DefaultView.ToTable
        Dim servicenumber As String = datatable_default_view.Rows.Item(e.RowIndex)("Service Number").ToString
'gets the service number of the selected row

        If _datatable.PrimaryKey.Length = 0 Then
            Dim keys(0) As DataColumn
            keys(0) = _datatable.Columns("Service Number")
            _datatable.PrimaryKey = keys
        End If

        Dim datarow_edited As DataRow = _datatable.Rows.Find(servicenumber)

        Try
            MsgBox("Record" + datarow_edited("service number") + " was edited")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error")
        End Try

我已将此代码放在DatagridView_CellEndEdit事件

问题:
使用键盘(即:按向下/向上箭头)退出编辑模式下的单元格时,不会初始化'data_row edited'变量。 如果我使用鼠标它按预期工作。为什么是这样 ?这是一个已知的错误我正在使用VB.net 2008.请帮忙

我上传了一个示例项目,其中包含示例数据here。如果可能,请查看。

2 个答案:

答案 0 :(得分:1)

尝试使用VS 2010的示例解决方案,它正在按预期工作。当使用箭头键切换行时,DataRow也会正确初始化。

编辑:

现在有你,抱歉。

在幕后看起来像是一些异步问题。

也许处理数据表本身的RowChanged事件可能是一种解决方法

Imports System.Data.OleDb
Public Class Form1
    Private _datatable As DataTable
    Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Members Database.mdb;Persist Security Info=False"


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim connection As New OleDbConnection(conn)
        Dim adapter As OleDbDataAdapter


        Dim _branchname As String = "A BAUR"
        Dim cmd As String = "Select [Service Number] ,[Name], [Gender], [Subscription]  from " + _branchname.Insert(0, "[") + "]"
        adapter = New OleDbDataAdapter(cmd, conn)
        _datatable = New DataTable
        adapter.Fill(_datatable)


        If _datatable.PrimaryKey.Length = 0 Then

            Dim keys(0) As DataColumn
            keys(0) = _datatable.Columns("Service Number")
            _datatable.PrimaryKey = keys
        End If


        AddHandler _datatable.RowChanged, AddressOf _datatable_RowChanged

        DataGridView1.DataSource = _datatable

    End Sub


    Private Sub _datatable_RowChanged(sender As Object, e As System.Data.DataRowChangeEventArgs)

        Dim servicenumber = e.Row("Service Number")

        Dim datarow_edited As DataRow = _datatable.Rows.Find(servicenumber)

        Try 
            MsgBox("Record" + datarow_edited("service number") + " was edited")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error")
        End Try
    End Sub

End Class

答案 1 :(得分:0)

Dim servicenumber As String =  _datatable.Rows(e.RowIndex)("Service Number").ToString()