Why is my SQL function not working in Visual Basic 2010?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
My project involves working with a database in a datagridview. The function below is the function for adding new entries to the database, with the fields for the new entry being located in text boxes.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click<br/>
Try<br/>
<br/>
Dim sn As Integer<br/>
Dim srn As String<br/>
Dim first As String<br/>
Dim hr As String<br/>
Dim avg As Integer<br/>
<br/>
sn = Val(txtSN.Text)<br/>
srn = txtSRN.Text<br/>
first = txtFN.Text<br/>
hr = txtHR.Text<br/>
avg = Val(txtAV.Text)<br/>
<br/>
Dim strsql As String<br/>
strsql = "INSERT INTO Table1 VALUES (@sn,@srn,@first,@hr,@avg)"<br/>
Dim connection As New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;User Instance=True")<br/>
Dim command As New SqlCommand(strsql, connection)<br/>
<br/>
<br/>
Dim prmsn As New SqlParameter("@sn", SqlDbType.Int)<br/>
prmsn.Value = CType(sn, Integer)<br/>
<br/>
Dim prmsrn As New SqlParameter("@srn", SqlDbType.NChar)<br/>
prmsrn.Value = srn<br/>
<br/>
Dim prmfirst As New SqlParameter("@first", SqlDbType.NChar)<br/>
prmfirst.Value = first<br/>
<br/>
Dim prmhr As New SqlParameter("@hr", SqlDbType.NChar)<br/>
prmhr.Value = hr<br/>
<br/>
Dim prmavg As New SqlParameter("@avg", SqlDbType.Int)<br/>
prmavg.Value = CType(avg, Integer)<br/>
<br/>
command.Parameters.Add(prmsn)<br/>
command.Parameters.Add(prmsrn)<br/>
command.Parameters.Add(prmfirst)<br/>
command.Parameters.Add(prmhr)<br/>
command.Parameters.Add(prmavg)<br/>
<br/>
connection.Open()<br/>
<br/>
Using (connection)<br/>
command.ExecuteNonQuery()<br/>
connection.Close()<br/>
End Using<br/>
<br/>
Try<br/>
Me.Validate()<br/>
Me.Table1BindingSource.EndEdit()<br/>
Me.Table1TableAdapter.Update(Me.Database1DataSet.Table1)<br/>
MsgBox("Update successful")<br/>
<br/>
Catch ex As Exception<br/>
MsgBox("Update failed")<br/>
End Try<br/>
<br/>
Catch ex As Exception<br/>
MessageBox.Show(ex.Message)<br/>
End Try<br/>
<br/>
DataGridView1.Update()<br/>
DataGridView1.Refresh()<br/>
<br/>
End Sub
The results are very weird when this code is used. First off, the datagridview does not immediately add the new entry to it. However, the next time the program is run, the new entry appears. However, the new entry does not actually become part of the database
(when I check the table, the entries are never there) but they do appear on the DataGridView. Usually after a few runs of the program, the entries that were inputted disappear completely.
I do not know what the problem with this code is. Can anyone point me in the right direction?

View the full article
 
Back
Top