windows form sometimes freez when looping all item in gridvi - vb.net

Trying to save all rows in DataGridView using For Each loop and the application sometimes freezes while I am not saving any rows. How can I solve this problem?
Using con As New SqlConnection(cs)
Using cmd As New SqlCommand
con.Open()
cmd.CommandTimeout = 120
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "[Stored_invoice]"
cmd.Parameters.Clear()
cmd.Connection = con
For Each row As DataGridViewRow In dgwold.Rows
If Not row.IsNewRow Then
If IsDBNull(row.Cells(6).Value) Then
xv = row.Cells(6).Value
Else
xv = DBNull.Value
End If
cmd.Parameters.AddWithValue("#Action", 0)
cmd.Parameters.AddWithValue("#invoice_id", invid)
cmd.Parameters.AddWithValue("#ExpireDate", xv)
cmd.Connection = con
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
End If
Next

Related

SQL Error Regarding apostrophe from datagridview using parameter in query

Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0))
end with
The value from the datagrid view contains an apostrophe where I get an error in ('s). Any work around with this?
EDIT:
This is the error:
SqlException was unhandled. Incorrect syntax near 's'.
EDIT 2: i've revised the code to this:
for 1=0 to datagridview.rows.count -1
Dim tname = datagridview.Rows(i)
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", sc.cells(0).value)
end with
con.Close()
con.Open()
If Not cmd.ExecuteNonQuery() > 0 Then
con.Close()
Exit For
End If
next
Error is still the same.
As it goes through all the values quickly in one go, I would make the connection once and change the value of the parameter for each iteration, like this:
Dim sql = "INSERT INTO [Schedule] ([Name]) VALUES(#sc)"
Using conn As New SqlConnection("your connection string"),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#sc",
.SqlDbType = SqlDbType.NVarChar,
.Size = -1})
conn.Open()
For i = 0 To dgv.Rows.Count - 1
Dim tname = dgv.Rows(i).Cells(0).Value.ToString()
cmd.Parameters("#sc").Value = tname
cmd.ExecuteNonQuery()
Next
End Using
Including the size of the parameter in its declaration helps SQL Server keep things tidy (it only needs one entry in the query cache).
The Using statement makes sure that the connection and command are disposed of properly when they are finished with.
The purpose of checking If Not cmd.ExecuteNonQuery() > 0 was not clear to me, so I didn't put that in.
(I used "dgv" as the name of the DataGridView.)
Try to replace the " ' " by " '' "
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters.AddWithValue("#sc", replace(sc.cells(0), "'", "''")
end with
/**** EDIT ****/
I will consider by the way that your code have a problem with the affectation of the value. You get the value into SC then try to get again the value from cell
Dim sc = datagridview.rows(0).cells(0).value
cmd = New SqlCommand("insert into Schedule (Name) values(#sc)", con)
with cmd
.Connection = con
.CommandType = CommandType.Text
.Parameters("#sc").value = sc.replace("'", "''")
end with

VB.NET wait until Query is done to to proceed to next code

I am trying to run a query/job and need to wait until the job/query is done running to continue onto the next line of code in the VB.NET application. How would I do this?
con.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "USE msdb; EXEC dbo.sp_start_job N'FWP1 Incremental Daily'"
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
con.Close()
(WAIT UNTIL FINISHES) - How do I Code this???
\\Continue Code...........
Application.UseWaitCursor = True
con.Open()
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = con
cmd.CommandText = "USE msdb; EXEC dbo.sp_start_job N'FWP1 Incremental Daily'"
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
con.Close()
Application.UseWaitCursor = False
MsgBox("Finished!")
Hope this will help.

cmd.ExecuteNonQuery() is not allowed

In my webmethod, i am updating the database. but while debugging the cursor escapes on cmd.ExecuteNonQuery(). my code is,
If tbl = "All" Then
cmd = New SqlCommand("update setbool set pos_val='False',valid_rp='False',Pos_save='False'", conn)
cmd.ExecuteNonQuery()
Return Nothing
Else
cmd = New SqlCommand("update setbool set " & tbl & "='True'", conn)
cmd.ExecuteNonQuery()
Return Nothing
End If
Any suggestion?
I found my own solution.
instead of
cmd = New SqlCommand("update setbool set pos_val='False',valid_rp='False',Pos_save='False'", conn)
cmd.ExecuteNonQuery()
Return Nothing
i changed
Using cmd1 As New SqlCommand("update setbool set pos_val='False',valid_rp='False',Pos_save='False'")
cmd1.CommandType = CommandType.Text
cmd1.Connection = conn
conn.Open()
cmd1.ExecuteNonQuery()
conn.Close()
End Using
Return Nothing

VB.net sql table not showing last rows

What I am doing-
Importing 406 rows into 5 sql tables from excel sheet.
After import, I am manually saving data one by one into each of the 5
tables on button click event and displaying on datagridview..
After saving each record, I am refreshing datagridview.
My problem -
Records are getting saved properly, but datagridview shows only
408 records, where actual no. of records are 412.
When viewed from server explorer also, only 408 records are
shown.
But table properties show that there are 412 rows.
This problem is with only first table.
my code:-
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into pd([Adm No],[DOA],[Name],[Course],[Fees Due],[Concession],[Contact No 1]," & _
"[Contact No 2],[E-Mail],[Year of Passing],[Address],[DOB],[College])" & _
" values(#admno,#doa,#name,#course,#totalfees,#concession,#contactno1,#contactno2,#email,#yop," & _
"#address,#dob,#college)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#doa", date_format.format_date(doa.Value.Date))
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#totalfees", txt_totalfees.Text)
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#contactno1", txt_contact1.Text)
cmd.Parameters.AddWithValue("#contactno2", txt_contact2.Text)
cmd.Parameters.AddWithValue("#email", txt_email.Text)
cmd.Parameters.AddWithValue("#yop", txt_yop.Text)
cmd.Parameters.AddWithValue("#address", txt_address.Text)
cmd.Parameters.AddWithValue("#dob", date_format.format_date(dob.Value.Date))
cmd.Parameters.AddWithValue("#college", txt_college.Text)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save fees details
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "INSERT into fees([Adm No],[Name],[Fees Due],[Fees Paid],[No of Installments]," & _
"[Installment Amounts],[Receipt Nos],[Dates of Transaction],[Mode],[Bank],[Due Date]" & _
",[Total Fees],[Concession],[Cheque No],[Course])" & _
" values(#admno,#name,#feesdue,#feespaid,#noi,#instamnt,#rcno,#dot,#mode,#bank,#dd," & _
"#total,#concession,#chqno,#course)"
cmd.Parameters.AddWithValue("#admno", i.ToString)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#feesdue", (CInt(txt_totalfees.Text) - CInt(txt_concession.Text)))
cmd.Parameters.AddWithValue("#feespaid", CInt(0))
cmd.Parameters.AddWithValue("#noi", CInt(0))
cmd.Parameters.AddWithValue("#instamnt", "")
cmd.Parameters.AddWithValue("#rcno", "")
cmd.Parameters.AddWithValue("#dot", "")
cmd.Parameters.AddWithValue("#mode", "")
cmd.Parameters.AddWithValue("#bank", "")
cmd.Parameters.AddWithValue("#dd", "")
cmd.Parameters.AddWithValue("#total", CInt(txt_totalfees.Text))
cmd.Parameters.AddWithValue("#concession", txt_concession.Text)
cmd.Parameters.AddWithValue("#chqno", "")
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
'save photo
If Not PictureBox1.Image Is Nothing Then
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
Else
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "Insert into img values(#adm,#name,#imge)"
Dim para As New SqlCeParameter("imge", SqlDbType.Image)
Dim ms As New MemoryStream
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer
para.Value = data
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.Add(para)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
End If
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into attend values(#adm,#name,#course,#dt,#stat)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#dt", "")
cmd.Parameters.AddWithValue("#stat", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
cmd.CommandText = String.Empty
cmd.Parameters.Clear()
cmd.CommandText = "insert into testdb values(#adm,#name,#course,#tname,#tdate,#marksob,#marksout)"
cmd.Parameters.AddWithValue("#adm", lb_admno.Text)
cmd.Parameters.AddWithValue("#name", txt_name.Text)
cmd.Parameters.AddWithValue("#course", combo_course.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#tname", "")
cmd.Parameters.AddWithValue("#tdate", "")
cmd.Parameters.AddWithValue("#marksob", "")
cmd.Parameters.AddWithValue("#marksout", "")
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.ExecuteNonQuery()
problem was in the code of importing records. I was reading cells of excel file and inserting them into five tables.
Problem arises only if I import records in all five tables one by one, but if I import records into only three tables then the problem doesn't arise.
This solved my problem, but I didn't happen to know the actual reason behind it. Why can't I import records into five tables one after another? If anyone finds the reason behind the error please comment.

SqlCommand (Using Statement / Disposing issue)

Take the following example...
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
From my research today is sounds as though this is basically okay but the SqlCommand is not being disposed of.
Question -> Which of the following examples is the best way to deal with this?
Example 2 - Dispose manually
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
cmd.Dispose()
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
Example 3 - Automatic disposing with the Using statement
Using cn As New SqlConnection(ConnectionString)
Try
Using cmd As New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
End Using
Catch ex As Exception
End Try
End Using
Example 4 - The same as example 3 but the Try/Catch is within the Using - does this make a difference?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand
Try
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 5 - The same as example 4 but the CommandText and cn are specified in the Using Statement - What advantage does this have?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection.Open()
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 6 - The same as example 5 but the connection is opened on cn instead of cmd. Is it better to open the connection on cmd if only one stored procedure is to be executed?
Using cn As New SqlConnection(ConnectionString)
cn.Open()
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection = cn
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
The DataAdapter.Fill command will open and close the connection itself, so you don't need the cmd.Connection.Open(). (Ref: the remarks section in http://msdn.microsoft.com/en-us/library/377a8x4t.aspx .)
Using Using for the SqlConnection has the effect of calling .Close on it for you.
The variable cmd becomes eligible for garbage collection once it is out of scope (or earlier if .NET determines it isn't going to be used again).
In your example 2, I'm not sure it's such a good idea to dispose of the cmd before the DataAdapter has used it.
[Information from user "JefBar Software Services" in Should I call Dispose on a SQLCommand object? ] At the time of writing, calling .Dispose on an SqlCommand has no effect because of the code in its constructor:
public SqlCommand() : base() {
GC.SuppressFinalize(this);
}