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")
Related
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
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
I want to Auto Increment the ID when I am adding new data to excel and this codes doesn't Auto Increment it's Only increment by 2 and i can't understand why please helpp thankssss
Dim Value As Integer
cn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Users\\Barbatos\\Desktop\\Book3.xlsx " + ";Extended Properties=Excel 12.0;")
cm = New OleDbCommand("SELECT MAX ([ID]) FROM [Sheet1$]", cn)
cn.Open()
Dim dr As OleDbDataReader = cm.ExecuteReader()
If dr.HasRows Then
dr.Read()
Value = dr(0)
Else
End If
dr.Close()
Dim str As String
Dim empid As Integer
Dim newNumber As Integer
str = "SELECT MAX([ID]) AS MAXIMUM FROM [Sheet1$]"
Dim cmd2 As OleDbCommand = New OleDbCommand(str, cn)
'Dim dr As OleDbDataReader
dr = cmd2.ExecuteReader
If dr.HasRows Then
While dr.Read()
If empid = IsDBNull(dr("MAXIMUM")) Then
newNumber = CInt(Val(empid)) + 1
End If
If newNumber = 0 Then
newNumber = 1
empid = CStr(newNumber)
ElseIf newNumber = 1 Then
newNumber = newNumber + 1
empid = CStr(newNumber)
Else
newNumber = newNumber + 1
empid = CStr(newNumber)
End If
End While
End If
dr.Close()
Me.Label2.Text = empid
To summarise my comments, I'd be doing this:
Dim nextId As Integer
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Barbatos\\Desktop\\Book3.xlsx;Extended Properties=Excel 12.0;"),
command As New OleDbCommand("SELECT MAX([ID]) FROM [Sheet1$]", connection)
connection.Open()
Dim currentId = command.ExecuteScalar()
nextId = If(currentId Is DBNull.Value, 1, CInt(currentId) + 1)
End Using
or, if it's supported, this:
Dim nextId As Integer
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Barbatos\\Desktop\\Book3.xlsx;Extended Properties=Excel 12.0;"),
command As New OleDbCommand("SELECT ISNULL(MAX([ID]), 0) FROM [Sheet1$]", connection)
connection.Open()
nextId = CInt(command.ExecuteScalar()) + 1
End Using
SOlVED
If dr.HasRows Then
dr.Read()
If IsDBNull(dr("MAXIMUM")) Then
empid = 1
Else
empid = CInt(dr("MAXIMUM")) + 1
End If
Else
empid = 1
End If
I am using SqlDataAdapter and SqlCommandBuilder to insert and update, and I want to use transaction to insert into two tables with this way but I have tried a lot and I didn't succeed
thanks
Dim sql = "select * from ReceiptOfItems where receiptCode=N'" & receiptCode.Text & "' "
Dim dta As New SqlClient.SqlDataAdapter(sql, con)
Dim ds As New DataSet
dta.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
' MsgBox("اسم االتصنيفل او رقمه موجود مسبقا ", MsgBoxStyle.Exclamation, "رسالة تنبيه")
receiptCode.Text = Format(Val(GetLastRecord("ReceiptOfItems", "receiptcode")) + 1, "REC0000000")
End If
Dim dr = dt.NewRow
dr!receiptCode = receiptCode.Text
dr!receiptDate = Format(receiptDate.Value, "yyyy/MM/dd")
' dr!receiptDate = receiptDate.Text
dr!supplierCode = GetsupplierCode(supplierName.Text)
dr!SupplierInvoiceCode = SupplierInvoiceCode.Text
dr!supplierInvoiceDate = Format(supplierInvoiceDate.Value, "yyyy/MM/dd")
'dr!supplierInvoiceDate = supplierInvoiceDate.Text
dr!TotalDiscount = Val(TotalDiscount.Text)
dr!TotalReceipt = Val(TotalReceipt.Text)
dr!TotalArabic = TotalArabic.Text
dr!SupplierInvoiceType = SupplierInvoiceType.Text
dr!salesTax = Val(salesTax.Text)
dr!note = note.Text
dr!status = True
dt.Rows.Add(dr)
Dim cmd As New SqlCommandBuilder(dta)
This should work for you:
con.Open()
Dim trans As SqlTransaction = con.BeginTransaction()
Try
Dim insertStr As String = "insert into ReceiptOfItems (receiptCode, receiptDate, etc.) values(#receiptCode, #receiptDate, #etc)"
Dim insertCmd As New SqlCommand(insertStr, con, trans)
For Each dc As DataColumn In dt.Columns
Dim param As New SqlParameter()
param.ParameterName = dc.ColumnName
param.SourceColumn = dc.ColumnName
insertCmd.Parameters.Add(param)
Next
dta.InsertCommand = insertCmd
dta.Update(ds)
trans.Commit()
con.Close()
Catch ex As Exception
trans.Rollback()
End Try
The DataAdapter class has an UpdateCommand and a DeleteCommand property which must be built appropriately if you are doing something other than inserting new rows.
I get the following error: No data exists for the row/column.
It should retrieve the image
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
dr.Close()
sSql = "select Pfile from Faculty where StId = '" & lab1id.Text & "'"
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader()
pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
pdr.Close()
The dr.GetValue(N) is zero-based ordinal. Change your indices:
While dr.Read()
lab1id.Text = dr.GetValue(0).ToString
lab1fname.Text = dr.GetValue(1).ToString
lab1lname.Text = dr.GetValue(2).ToString
lab1position.Text = dr.GetValue(3).ToString
lab1subject.Text = dr.GetValue(4).ToString
End While
While pdr.Read() ' | you got a typo here. Change `dr` to `pdr`.
Dim bits As Byte() = CType(pdr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
Consider changing your code to something like this:
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC;"
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
lab1id.Text = reader.Item("id").ToString
lab1fname.Text = reader.Item("fname").ToString
lab1lname.Text = reader.Item("lname").ToString
lab1position.Text = reader.Item("position").ToString
lab1subject.Text = reader.Item("subject").ToString
End While
End Using
End Using
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "select Pfile from Faculty where StId = #StId;"
command.Parameters.AddWithValue("#StId", lab1id.Text)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim bits As Byte() = CType(reader.Item("Pfile"), Byte())
Using stream As New MemoryStream(bits)
imgRetrieve.Image = Bitmap.FromStream(stream)
End Using
End While
End Using
End Using
The problem is you never execute pcmd, see the following two lines:
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader() ' cmd should be replaced with pcmd
I would suggest adding While...End While Statement when getting the values from dr and pdr. You also need to parameterize the second query to avoid SQL Injection.
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
End While
dr.Close()
sSql = "select Pfile from Faculty where StId = #StId"
Dim pcmd As New OleDbCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", lab1id.Text)
Dim pdr As OleDbDataReader = pcmd.ExecuteReader()
While pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
pdr.Close()