选择在dgv中添加/更新的最后一条记录

时间:2015-04-16 11:53:45

标签: vb.net

如何选择在datagridview中添加或更新的最后一条记录 这是我添加的方式

 Insert into table (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"

添加记录后我刷新dgv

("Select * from table")
    Form1.DGV.DataSource = SQLDataset1.Tables(0)

这就是我更新记录的方式

("Update table Set Name='" & txtT.Text & "' , DateEdit='" & Date.Now & "' Where Town= '" & txtT.Text & "'")

编辑:

Public Sub addIt(Name As String)
        Try
            Dim addStr As String = "Insert into tableName (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
            sqlcon.Open()
            SqlCom = New SqlCommand(addStr, sqlcon)
            SqlCom.ExecuteNonQuery()
            sqlcon.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

' Buton点击事件

  If Len(town) >= 3 Then
                        sql.addIt(town)
                        Msgbox("Added")
                        sql.resetDGV()
   End If

Public Sub resetDGV()
                sqlquery("Select * from tableName")
                Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub

1 个答案:

答案 0 :(得分:1)

www中有更简单的方法。但这是最短的......

Public Sub addIt(Name As String) as int
        Dim insertedID as int = -1
        Try
            Dim addStr As String = "Insert into tableName (Name, AddDate) OUTPUT INSERTED.ID values ('" & Name & "', '" & Date.Now & "')"
            sqlcon.Open()
            SqlCom = New SqlCommand(addStr, sqlcon)
            returnValue = Convert.ToInt32(SqlCom.ExecuteScalar())
            sqlcon.Close()

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        return insertedID 
End Sub

  If Len(town) >= 3 Then
     Dim insertedID as int = sql.addIt(town)
     If insertedID = -1 Then return

     Msgbox("Added")
     sql.resetDGV()
     'Select
     SelectLastInsertedRow(insertedID)
  End If

Public Sub resetDGV()
    sqlquery("Select * from tableName")
    Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub

Private Sub SelectLastInsertedRow(id as int)
    For Each row as DataGridViewRow in dgv.Rows
        'Check if row belongs to the ID
        if(row == id) Then
          'Select
          row.Select = true
        End if 
    End For
End Sub

此代码未经过测试。但它应该有效:P