我正在從數據表名車表中加載來自訪問數據庫的數據。此表具有carId爲自動增加的編號Vb.Net獲取數據表中的最後一個自動增量值
加載數據是這樣的:
Private Sub frmCar_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dsDataSet = New DataSet
loadCars()
bsCar = New BindingSource(dsDataSet, "car")
CarIDTextBox.DataBindings.Add(New Binding("text", bsCar, "carId"))
BrandTextBox.DataBindings.Add(New Binding("text", bsCar, "brand"))
ModelTextBox.DataBindings.Add(New Binding("text", bsCar, "model"))
RegNoTextBox.DataBindings.Add(New Binding("text", bsCar, "regNo"))
InsIDTextBox.DataBindings.Add(New Binding("text", bsCar, "insId"))
DailyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "dailyCharge"))
WeeklyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "weeklyCharge"))
MonthlyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "monthlyCharge"))
YearlyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "yearlyCharge"))
TransmissionTextBox.DataBindings.Add(New Binding("text", bsCar, "transmission"))
ColorTextBox.DataBindings.Add(New Binding("text", bsCar, "color"))
RemarkTextBox.DataBindings.Add(New Binding("text", bsCar, "remark"))
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Sub loadCars()
Dim sql As String
Try
oledbConn = New OleDbConnection(oledbConnString)
oledbConn.Open()
sql = "select * from car order by carId"
daCar = New OleDbDataAdapter(sql, oledbConn)
daCar.Fill(dsDataSet, "car")
'----------------------------------------------------------------------
oledbConn.Close()
Catch ex As Exception
oledbConn.Close()
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
Try
bsCar.AddNew()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
Me.Validate()
bsCar.EndEdit()
daCar.Update(dsDataSet.Tables("car"))
MsgBox("Car saved successfully")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
現在,當我添加一個新的汽車,並保存它,一切都運行完美。但是我需要添加的新車的車型在添加後立即顯示。我怎麼能不查詢數據庫?謝謝
不查詢數據庫?你不能(至少使用Access)。 – Steve
正如史蒂夫說,與Access,你將需要再次查詢數據庫。基本上發送一個查詢選擇carID,其中regNo =您剛剛添加的regNo。在後場,因爲regNo將是唯一的(除非你將車牌從汽車轉移到汽車),那麼regNo可能是主鍵,你不需要AutoNumber字段。 – Mych
Access支持'SELECT @@ IDENTITY'來獲得最後一個自動增量,但這裏的問題是Adapter.Update命令,它不會給我們一個開放的連接。需要做一些測試 – Steve