2015-04-16 39 views
0

如何选择被添加或更新的DataGridView 最后一条记录这是我怎么添加选择最后一条记录添加/更新DGV

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 

“布顿单击事件

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 
+0

请问您可以将整个代码发布在一个区块中吗? – C0d1ngJammer

+0

@manuchao我会尽我所能,但是这些代码都是围绕着表单分裂的。 –

+0

现在我们只需要你的问题,问题...... P – C0d1ngJammer

回答

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

+0

它有很多修复此代码但最终不工作。调用它时,您需要将id发送给sub。也不能比较行和id类型的字符串。对于循环不工作像这样:(:( –

+0

更新。当然,你必须做一些工作,我无法测试它。 – C0d1ngJammer