這看起來像一個簡單的修復,但我無法弄清楚。我試圖在subForm(NewTournament)上添加按鈕單擊事件,向數據庫添加一條記錄,然後通知一個數據網格,該數據網格自動列出來自同一數據庫的記錄(網格在HomeForm中列出)。刷新數據網格視圖
我很高興能夠更新數據庫並調用新窗口。但我無法讓它刷新該數據網格的任何東西。我知道我應該清除數據網格,獲取更改,然後重新填充網格。但每次我這樣做,代碼都不會更新。此外,我可以很好地看到記錄正在被添加。
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' Check the form for errors, if none exist.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd, cmd1 As OleDbCommand
Dim icount As Integer
Dim str, str1 As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\Paul Williams III\Documents\Visual Studio 2010\Projects\Everything OP Client\Everything OP Client\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
str1 = "select @@Identity"
icount = cmd.ExecuteNonQuery
cmd1 = New OleDbCommand(str1, cn)
Counter = CInt(cmd1.ExecuteScalar)
MessageBox.Show(Counter & " was the last inserted id")
'displays number of records inserted
HomeForm.MasterDataSet.Clear()
HomeForm.MasterDataSet.GetChanges()
HomeForm.TournamentsTableAdapter.Fill(HomeForm.MasterDataSet.Tournaments)
HomeForm.DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow
n.TournID = Counter
n.Show(HomeForm)
End Sub
當你說參數化查詢時,你是什麼意思? – 2012-02-24 21:14:46
而不是串聯你的值,你把'?'作爲佔位符,然後設置參數值。這可以解決問題,比如你的比賽名稱是「O'Brien's Cup」,同時也消除了潛在的[SQL注入](http://xkcd.com/327/)攻擊。這裏是c#的Access [示例](http://stackoverflow.com/questions/9401888/parameterized-query-for-inserting-values)。對不起,我找不到任何VB.NET訪問,但它並沒有完全不同。 – 2012-02-24 21:24:23
當我使用你提供的代碼時,我得到一個錯誤:「重載解析失敗,因爲沒有可訪問的'AddTournamentsRow'接受這個數量的參數編輯:我只是回答我自己的問題顯然,MasterDataSet沒有所有這些參數(還是新的) – 2012-02-24 23:12:16