2015-04-16 157 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

相關問題