Executing update query inside loop - sql

cmd = New SqlCommand("select enrollment,total_fee,discount,net_fee from stu_dtl", openConnection())
' dr = cmd.ExecuteReader
adpt = New SqlDataAdapter(cmd)
adpt.Fill(ds, "stu_dtl")
dt = ds.Tables("stu_dtl")
For i = 0 To dt.Rows.Count - 1
cmd = New SqlCommand("update stu_dtl set net_fee = '" & (Val(dt.Rows(i).Item("total_fee")) - Val(dt.Rows(i).Item("discount"))) & "' where enrollment = '" & dt.Rows(i).Item("enrollment") & "'", openConnection())
cmd.ExecuteNonQuery()
Next
when I execute this code for more than 150 records "Nothing happens"......what am i doing wrong??is there any other way to update??

I'm not sure what you are doing wrong. But try this code. If an error occur it ensure rollback of the database. Note that I assume that the datatype of the net_fee and enrollment columns are Integer.
Using connection As SqlConnection = New SqlConnection("TODO: Set connection string.")
Dim table As DataTable = New DataTable("stu_dtl")
Dim [error] As Exception = Nothing
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "SELECT [enrollment], [total_fee], [discount], [net_fee] FROM [stu_dtl];"
Using adapter As New SqlDataAdapter(command)
adapter.Fill(table)
End Using
End Using
Using transaction As SqlTransaction = connection.BeginTransaction()
Try
Dim net_fee As Integer = 0
Dim enrollment As Integer = 0
For Each row As DataRow In table.Rows
net_fee = (CInt(row.Item("total_fee")) - CInt(row.Item("discount")))
enrollment = CInt(row.Item("enrollment"))
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "UPDATE [stu_dtl] SET [net_fee] = #net_fee WHERE [enrollment] = #enrollment;"
command.Parameters.AddWithValue("#net_fee", net_fee)
command.Parameters.AddWithValue("#enrollment", enrollment)
command.ExecuteNonQuery()
End Using
Next
transaction.Commit()
Catch ex As Exception
[error] = ex
transaction.Rollback()
End Try
End Using
If (Not table Is Nothing) Then
table.Dispose()
table = Nothing
End If
If (Not [error] Is Nothing) Then
Throw [error]
End If
End Using
Edit
Come to think of it, you might want to change the net_fee column to a computed column. The formula would simply be ([total_fee] - [discount]).

Related

Search database based on datagridview column?

Database search based on a specific column of Datagrid View results in finding the first row in the search interval, and this row is not my goal ... Why does a row-by-row search find only the first row?
i am working with vb.net 2015 & sql server 2014
This is my attempt to write a search code
Please help me..
Try
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim row As DataGridViewRow = DataGridView1.Rows(i)
If DataGridView1.Rows.Count <> 0 Then
If CBool(row.Cells("انتخاب").Value) = True Then
Dim rd As SqlDataReader
Dim con As New SqlConnection()
con.ConnectionString = (ConfigurationManager.ConnectionStrings("constr").ConnectionString)
con.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT F_Takhsise_SatheTafzili_B_Moin.ID,F_Takhsise_SatheTafzili_B_Moin.Acckind,
F_Takhsise_SatheTafzili_B_Moin.StmoinName,
F_Takhsise_SatheTafzili_B_Moin.UkolCode,
F_Takhsise_SatheTafzili_B_Moin.UmoinName,
F_Takhsise_SatheTafzili_B_Moin.Code_Sathe5,
F_Takhsise_SatheTafzili_B_Moin.Sathe5,
F_Takhsise_SatheTafzili_B_Moin.Code_Sathe6,
F_Takhsise_SatheTafzili_B_Moin.Sathe6,
F_Takhsise_SatheTafzili_B_Moin.Id_F_AnvaeSanadeHesabdari,
F_Takhsise_SatheTafzili_B_Moin.name
from F_Takhsise_SatheTafzili_B_Moin
where F_Takhsise_SatheTafzili_B_Moin.name = '" & row.Cells(8).Value.ToString() & "'"
cmd.Connection = con
rd = cmd.ExecuteReader
If rd.HasRows = True Then
Do
While rd.Read()
ID_code_Sathe5 = rd("code_Sathe5").ToString
ID_acckind = rd("acckind").ToString
ID_ukolcode = rd("ukolcode").ToString
ID_F_Takhsise_SatheTafzili_B_Moin = rd("id").ToString
End While
Loop While rd.NextResult
End If
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

I want a quick solution about adding a new row to datagraidview

I have a DataGridView and I'm adding a new row. But, when I add the new row it deletes the current row and replaces it.
This is the code
Try
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("SELECT ItemID, RTRIM(DishName),'1',Rate from Dish where ItemID like '" & TextBox1.Text & "' order by DishName", con)
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While (rdr.Read() = True)
DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3))
Dim num1 As Double
num1 = Val(DataGridView1.Rows(0).Cells("Qty").Value) * Val(DataGridView1.Rows(0).Cells("Rate").Value)
num1 = Math.Round(num1, 2)
DataGridView1.Rows(0).Cells("Amount").Value = num1
End While
TotalCalc()
Compute()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I am having a little problem following your question
Suggestion Don't tell us you want a quick solution
If you are changing the value in the DB use Update
Here is some code to add values to a DataGridView with SQLite
The SELECT statement is a little odd due to another issue in my Project
Just use your SELECT also Welcome to Stackoverflow
Private Sub ViewSearches()
Dim intID As Integer
Dim strCodeDesc As String
Dim strUIProject As String
Dim strCodeType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
If gvTxType = "View" Then
cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSCT
ElseIf gvTxType = "All" Then
cmd.CommandText = "SELECT * FROM CodeTable"
End If
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
intID = CInt((rdr("CID")))
strCodeDesc = rdr("cvCodeDesc").ToString
strUIProject = rdr("cvUIProject").ToString
strCodeType = rdr("cvCodeType").ToString
dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
rowCount += 1
End While
dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 12 Then
maxRowCount = 12 - rowCount
For iA = 1 To maxRowCount
dgvSelCode.Rows.Add(" ")
Next
End If
End Using
End Using
End Sub

There is no row at position 0 and System.IndexOutOfRangeException

Error :
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in System.Data.dll and also showing a :There is no row at
position 0
Dim mycn As New SqlConnection(connection)
Dim DT As New DataTable
mycn.Open()
Dim Adapter As New SqlDataAdapter("SELECT * FROM tblUser where username ='" & txtRet.Text & "'", connection)
Adapter.Fill(DT)
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
Dim bytBLOBData() As Byte = _
DT.Rows(0)("userimage")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
UserPictureBox.Image = Image.FromStream(stmBLOBData)
mycn.Close()
This error indicates that no rows were returned and since you're trying to get the first row (...DT.Rows(0)...) it is throwing the error.
My first suggestion would be to wrap your code in Using statements for all of the objects that implement iDisposable. My second suggestion would be to utilize a parameterized query. My last suggestion would be to check if Rows(0) exists before trying to access it.
Here is a quick example:
'Declare the connection object
Dim con As SqlConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = New SqlConnection(connection)
'Create a new instance of the command object
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM [tblUser] WHERE [username]=#username;", con)
'Parameterize the query
cmd.Parameters.AddWithValue("#username", txtRet.Text)
'Open the connection
con.Open()
'Declare a new adapter to fill the data table
Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
adapter.Fill(DT)
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If DT.Rows.Count > 0 Then
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
End If

I am getting this error "There is no row at position 0." vb.net as the frontend and sql server 2008 as the db

This is my code, I m getting error "There is no row at position 0."
Sub loadservicetype()
Dim str As String = "SELECT servicename FROM tbl_activity WHERE activity= '" & CmbActivity.Text & "' "
Dim dt As New DataTable
Dim sdr As New SqlDataAdapter(str, connection)
sdr.Fill(dt)
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End Sub
First thing is Always Use SQL Parameter to AVOID SQL injection
Like this
Dim commandText As String = "SELECT servicename FROM tbl_activity WHERE activity=#ID"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
command.Parameters.Add("#ID", SqlDbType.Int).Value = ID
Try
connection.Open()
Dim rowsAffected As String = command.ExecuteNonQuery()
Catch ex As Exception
throw
End Try
End Using
MSDN SOURCE
Your DataTable is Doesn't Return any rows which You Are Trying to Access
If dt IsNot Nothing Then
If dt.Row.Count>0 Then
TxtServiceType.Text = dt.Rows(0)("servicename").ToString
End If
End If

SQL Update with where clause with variables from VS2010 Winforms

I am trying to do an update query from a winform with two variables without using a dataset.
I assign both of my variable and then run the query but it keeps giving the error that zcomp is not a valid column name. Which of course is true but I tell it which column before I say = zcomp. Below is my code that is running the query.
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - zamnt WHERE [ComponentID] = zcomp"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
I have tried it several different ways. It works just fine if I take out the zamnt and zcomp and put the actual number values that are in the variables. Please help I've been searching all day for a way to use the variables with this update query.
Thanks,
Stacy
You are probably looking for how to use parameters in ADO.NET. For your example, it can look like this:
cmd.Parameters.Add("#zamnt", zamnt);
cmd.Parameters.Add("#zcomp", zcomp);
Put these two lines anywhere before ExecuteNonQuery.
Because parameters need a # prefix, you would also need to change your query to say #zamnt instead of just zamnt, and same for zcomp:
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
In addition to using parameters, the "Using" statement closes the connection and disposes resources:
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Try
Using con As New SqlConnection("Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True")
con.Open()
Using cmd As New SqlCommand
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] - #zamnt WHERE [ComponentID] = #zcomp"
cmd.Parameters.AddWithValue("#zamt", zamnt)
cmd.Parameters.AddWithValue("#zcomp", zcomp)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try
have u tried this?
Dim zamnt As Integer = WopartsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim zcomp As Integer = gridRow.Cells(0).Value
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=MNT-MGR-2\SQLEX;Initial Catalog=MT;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.sparts SET [dbo.sparts.QtyonHand] = [dbo.sparts.QtyonHand] -" + zamnt + " WHERE [ComponentID] =" + zcomp
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
gridRow.Cells(4).Value = "Yes"
End Try