Update table in sql database from listview items - vb.net

Hello folks am trying read from the table identify a specific column if not YES then update my table using items from listview
Public Sub FeesFromSetFees(lst As ListView, Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim item As New ListViewItem(txtbal.Text)
item.SubItems.Add(txtID.Text)
lst.Items.Add(item)
Dim lstId As New List(Of String)
Dim lstBalance As New List(Of String)
For Each li As ListViewItem In lst.Items
lstId.Add(li.SubItems(0).ToString)
lstBalance.Add(li.SubItems(1).ToString)
Next
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar)
.Add("#ID", SqlDbType.VarChar)
End With
cn.Open()
For index = 0 To lstId.Count - 1
cmd.Parameters("#Balance").Value = lstBalance(index)
cmd.Parameters("#ID").Value = lstId(index)
cmd.ExecuteNonQuery()
Next
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
I get my successful message but nothing really happen to data in the table

Public Sub FeesFromSetFees(Amt As String, Year As String, Clss As String, Term As String, Mode As String)
Dim txtID As New TextBox
Dim txtbal As New TextBox
Dim toText As New TextBox
Dim add As New TextBox
Try
con = New SqlConnection(My.Settings.DeseretConnectionString)
con.Open()
sql = "SELECT * FROM Fees"
command = New SqlCommand(sql, con)
reader = command.ExecuteReader
While reader.Read()
toText.Text = reader.Item("scholarship").ToString
If toText.Text.ToUpper <> "YES" Then
txtID.Text = reader.Item("id").ToString
add.Text = reader.Item("balance").ToString
txtbal.Text = CType(Amt.Trim, Double) + CType(add.Text.Trim, Double)
Dim Sql = "Update fees Set class = #Class, year = #Year, mode = #Mode,term = #Term, balance = #Balance where id = #ID"
Using cn As New SqlConnection(My.Settings.DeseretConnectionString)
Using cmd As New SqlCommand(Sql, cn)
With cmd.Parameters
.Add("#Class", SqlDbType.VarChar).Value = Clss
.Add("#Year", SqlDbType.VarChar).Value = Year
.Add("#Mode", SqlDbType.VarChar).Value = Mode
.Add("#Term", SqlDbType.VarChar).Value = Term
.Add("#Balance", SqlDbType.VarChar).Value = txtbal.Text
.Add("#ID", SqlDbType.VarChar).Value = txtID.Text
cn.Open()
cmd.ExecuteNonQuery()
End With
End Using
End Using
MessageBox.Show("successful")
End If
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

Related

How to update specific row using checkbox?

This is what I've tried. This works for checkbox value only and all displayed data will be updated.
Public Sub updateDGV()
Dim id As String
Dim cb As String
Dim time As String
Dim str As String
Dim mycon As New SqlConnection(ConString)
Try
mycon.Open()
For Each row As DataGridViewRow In dgv.Rows
row.Cells(22).Value = Date.Now.ToString("MM/dd/yyyy HH:mm:ss tt")
id = row.Cells(0).Value.ToString
cb = row.Cells(1).Value.ToString
time = row.Cells(22).Value.ToString
str = "UPDATE GuardMonitoring SET EmploymentStatus =#EmpStat,
ModifiedBy =#ModifiedBy, ModifyDate =#ModifyDate WHERE
(Employee_Id =#EmpId)"
Dim cmd As SqlCommand = New SqlCommand(str, mycon)
cmd.Parameters.AddWithValue("#EmpId", SqlDbType.VarChar).Value = id
cmd.Parameters.AddWithValue("#EmpStat", SqlDbType.VarChar).Value = cb
cmd.Parameters.AddWithValue("#ModifiedBy", SqlDbType.VarChar).Value = UserPass.txtfull2.Text
cmd.Parameters.AddWithValue("#ModifyDate", SqlDbType.VarChar).Value = time
cmd.ExecuteNonQuery()
Next
mycon.Close()
Catch ex As Exception
showmsg.ForeColor = Color.LightCoral
showmsg.Text = "Rows not found!"
MsgBox(ex.Message)
End Try
End Sub
Expected output: update only when changing the specific value of checkbox.
Do you mean that you want to update only the row that have checkboxes turned ON?
If so, it can be determined by the value of the checkbox cell.
For example, like this.
Public Sub updateDGV()
Dim id As String
Dim cb As String
Dim time As String
Dim str As String
Dim mycon As New SqlConnection(ConString)
Try
mycon.Open()
For Each row As DataGridViewRow In dgv.Rows
If Convert.ToBoolean(row.Cells("your checkbox column name").Value) Then
row.Cells(22).Value = Date.Now.ToString("MM/dd/yyyy HH:mm:ss tt")
id = row.Cells(0).Value.ToString
cb = row.Cells(1).Value.ToString
time = row.Cells(22).Value.ToString
str = "UPDATE GuardMonitoring SET EmploymentStatus =#EmpStat,
ModifiedBy =#ModifiedBy, ModifyDate =#ModifyDate WHERE
(Employee_Id =#EmpId)"
Dim cmd As SqlCommand = New SqlCommand(str, mycon)
cmd.Parameters.AddWithValue("#EmpId", SqlDbType.VarChar).Value = id
cmd.Parameters.AddWithValue("#EmpStat", SqlDbType.VarChar).Value = cb
cmd.Parameters.AddWithValue("#ModifiedBy", SqlDbType.VarChar).Value = UserPass.txtfull2.Text
cmd.Parameters.AddWithValue("#ModifyDate", SqlDbType.VarChar).Value = time
cmd.ExecuteNonQuery()
End If
Next
mycon.Close()
Catch ex As Exception
showmsg.ForeColor = Color.LightCoral
showmsg.Text = "Rows not found!"
MsgBox(ex.Message)
End Try
End Sub

Passing textbox control as argument

The following code contains a function that retrieves values from database and places them in four textboxes for ex: txtCash, txtDebt, txtPayment, txtBalance. so instead of writing the textboxes inside the function, I want to replace them with placeholders and return the values to the form that contains these textboxes
Public Sub LoadTotals()
Dim AfCashAmount As Double
Dim AfDebtAmount As Double
Dim AfPayment As Double
Try
sqL = "SELECT InvoiceID, SUM(InvoiceAmount) As Total FROM Invoice WHERE PaymentType = 'Cash' AND AccountType='AF' GROUP BY InvoiceID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfCashAmount = 0
Do While dr.Read = True
AfCashAmount = AfCashAmount + dr(1)
Loop
'*************************************************************************
sqL = "SELECT InvoiceID, SUM(InvoiceAmount) As Total FROM Invoice WHERE PaymentType = 'Debt' AND AccountType='AF' GROUP BY InvoiceID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfDebtAmount = 0
Do While dr.Read = True
AfDebtAmount = AfDebtAmount + dr(1)
Loop
'*************************************************************************
sqL = "SELECT PaymentID, SUM(PaymentAmount) FROM Payment WHERE Currency='AF' GROUP BY PaymentID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfPayment = 0
Do While dr.Read = True
AfPayment = AfPayment + dr(1)
Loop
With frmStatistics
.txtAFCash.Text = Format(AfCashAmount, "N2").ToString()
.txtAFDebt.Text = Format(AfDebtAmount, "N2").ToString()
.txtAFPayment.Text = Format(AfPayment, "N2").ToString()
.txtAFBalance.Text = Format(AfDebtAmount - AfPayment, "N2").ToString()
End With
Catch ex As Exception
MsgBox(ex.ToString)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
You can use the following returning a Dictionary:
Public Function LoadTotals() As Dictionary(Of String, String)
Dim AfCashAmount As Double
Dim AfDebtAmount As Double
Dim AfPayment As Double
Try
sqL = "SELECT InvoiceID, SUM(InvoiceAmount) As Total FROM Invoice WHERE PaymentType = 'Cash' AND AccountType='AF' GROUP BY InvoiceID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfCashAmount = 0
Do While dr.Read = True
AfCashAmount = AfCashAmount + dr(1)
Loop
'*************************************************************************
sqL = "SELECT InvoiceID, SUM(InvoiceAmount) As Total FROM Invoice WHERE PaymentType = 'Debt' AND AccountType='AF' GROUP BY InvoiceID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfDebtAmount = 0
Do While dr.Read = True
AfDebtAmount = AfDebtAmount + dr(1)
Loop
'*************************************************************************
sqL = "SELECT PaymentID, SUM(PaymentAmount) FROM Payment WHERE Currency='AF' GROUP BY PaymentID"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader
AfPayment = 0
Do While dr.Read = True
AfPayment = AfPayment + dr(1)
Loop
'The following to return string values.
Dim dictTotals As New Dictionary(Of String, String)
dictTotals.Add("CashAmount", Format(AfCashAmount, "N2").ToString())
dictTotals.Add("DebtAmount", Format(AfDebtAmount, "N2").ToString())
dictTotals.Add("Payment", Format(AfPayment, "N2").ToString())
dictTotals.Add("Balance", Format(AfDebtAmount - AfPayment, "N2").ToString())
''The following to return the double values.
''In this case change the return value to Dictionary(Of String, Double)
'Dim dictTotals As New Dictionary(Of String, Double)
'dictTotals.Add("CashAmount", AfCashAmount)
'dictTotals.Add("DebtAmount", AfDebtAmount)
'dictTotals.Add("Payment", AfPayment)
'dictTotals.Add("Balance",AfDebtAmount - AfPayment)
Return dictTotals
Catch ex As Exception
MsgBox(ex.ToString)
Return Nothing
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
So you can use the result on any other Form you want like the following:
Dim dictTotals As Dictionary(Of String, String) = LoadTotals()
txtAFCash.Text = dictTotals("CashAmount")
txtAFDebt.Text = dictTotals("DebtAmount")
txtAFPayment.Text = dictTotals("Payment")
txtAFBalance.Text = dictTotals("Balance")

How to add dynamic Data in to the datagridviewcombobox column?

I am Developing VB.net application.
In that application I take DataGirdView to display data.
I took DataSource property of the datagridview to display 3 columns' data directly from database.
After those columns I add another DataGridViewComboBoxColumn. Then I a want to add dynamic the data into that ComboBoxColumn.
how to do this?
Private Function CreatComboBoxWithEnum() As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Dim adpter As New SqlDataAdapter
Dim ds As New DataTable
Try
Sqlconn.Open()
Dim Query As String
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr ='" & val & "' "
COMMAND = New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = COMMAND
adpter.Fill(ds)
combo.DataSource = ds
combo.DataPropertyName = "OperationNo"
combo.Name = "OperationNo"
OperationNo.ValueMember = "OperationNo"
OperationNo.DisplayMember = "OperationNo"
Next
Sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return combo
End Function
Private Sub load_operationNo()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Try
op.Name = "OperationNo"
DataGridView1.Columns.Add(op)
Sqlconn.Open()
Dim Query As String
Dim i As Integer = 0
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim OPno As New DataGridViewComboBoxCell
With OPno
Dim adpter As New SqlDataAdapter
Dim dt As New DataTable
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr = " & val & " order by sr"
Using cmd As New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = cmd
adpter.Fill(dt)
End Using
.DataSource = dt
.ValueMember = "OperationNo"
.DisplayMember = "OperationNo"
DataGridView1.Rows(i).Cells("OperationNo") = OPno
i = i + 1
End With
Next
Sqlconn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End Sub
This is the code to add dynamically add the data into DatagridViewComboboxColumn

Sending updates from datagridview to existing row in database

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try