这是我在这里的第一篇文章,如果我违反规则并需要稍后澄清一些事情,请原谅我。我的问题是我正在使用 Visual Basic 2008 并且有一个 Windows 窗体,该窗体具有多个绑定到数据视图的文本框。我能够很好地编辑数据,并将数据提交到 SQL 2005 express 数据库。此外,只要我不退出程序,我就可以添加一条持续存在的记录。一旦我编辑新记录就会丢失。因此,基本上,正在提交编辑,但没有添加。这是我正在使用的代码。感谢您的时间和考虑。
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Cursor = Cursors.WaitCursor
Try
cn = New SqlConnection(sConnString)
cn.Open()
' Open the Master table
da = New SqlDataAdapter("SELECT * FROM CAMaster;", cn)
ds = New DataSet
da.Fill(ds, "Master")
dv = New DataView(ds.Tables("Master"))
cm = CType(Me.BindingContext(dv), CurrencyManager)
dv.AllowNew = True
dv.AllowEdit = True
dv.AllowDelete = True
' Bind the form Textboxes to the Master table dataview and assign formatting
Dim ctl As Control
For Each ctl In Controls
If TypeOf ctl Is TextBox Then
If ctl.Tag <> "" Then
Select Case ctl.Tag
Case "Date"
ctl.DataBindings.Add("Text", dv, ctl.Tag, True, DataSourceUpdateMode.OnValidation, False, "MM/dd/yyyy")
Case Else
ctl.DataBindings.Add("Text", dv, ctl.Tag, True, DataSourceUpdateMode.OnValidation, False, "C2")
End Select
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Form Load Error")
End
End Try
Me.Cursor = Cursors.Default
End Sub
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
dv.RowFilter = ""
dv.AddNew()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information, "Add Error")
End Try
End Sub
Private Sub cmdOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
Me.Cursor = Cursors.WaitCursor
Dim i As Integer
Try
Me.Validate()
cm.EndCurrentEdit()
cb = New SqlCommandBuilder(da)
da.Update(ds, "Master")
ds.Tables("Master").AcceptChanges()
Catch ex As Exception
MsgBox(ex.Message)
End Try
SetButtons(True)
If mbAddNewFlag Then
Me.cmbDate.SelectedItem = Me.txtDate.Text
End If
Me.Cursor = Cursors.Default
End Sub