attempetd to dived by zero print crystal reports - vb.net

I Have one Project in VB.net i Print Barcode Label, But I have one Problem I can't Solve, When I show Reports In ReportViewer work FINE but when i try to PRINT display this ERROR "attempted to divide by zero" "Crystal Report Windows Form Viewer"
I don't have any formula in Report just Parameters!
Try
If listView1.CheckedItems.Count > 0 Then
Dim Condition As String = ""
Dim Condition1 As String = ""
For I = 0 To listView1.CheckedItems.Count - 1
Condition += String.Format("'{0}',", listView1.CheckedItems(I).Text)
Condition1 += String.Format("'{0}',", listView1.CheckedItems(I).SubItems(3).Text)
Next
Condition = Condition.Substring(0, Condition.Length - 1)
Condition1 = Condition1.Substring(0, Condition1.Length - 1)
Cursor = Cursors.WaitCursor
Timer1.Enabled = True
con = New SqlConnection(cs)
con.Open()
Dim st As String = "Select Barcode,Productname,(SalesPrice) as SalesRate from Product where ProductCode in (" & Condition & ") "
For j As Integer = 1 To Int32.Parse(Val(txtNoOfCopies.Text)) - 1
st = st & "Union all Select Barcode,Productname,(SalesPrice) as SalesRate from Product where ProductCode in (" & Condition & ")"
Next
cmd = New SqlCommand(st, con)
adp = New SqlDataAdapter(cmd)
dtable = New DataTable()
adp.Fill(dtable)
con.Close()
ds = New DataSet()
ds.Tables.Add(dtable)
ds.WriteXmlSchema("BarcodeLabelPrinting1.xml")
Dim rpt As New rptBarcodeLabelPrinting1
rpt.SetDataSource(ds)
rpt.SetParameterValue("p1", txtCompany.Text)
rpt.SetParameterValue("p2", txtCurrencyCode.Text)
frmReport.CrystalReportViewer1.ReportSource = rpt
frmReport.ShowDialog()
rpt.Close()
rpt.Dispose()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try

Related

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

Displaying multiple records

Private Sub Line_Change2()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("Id")
Cmb1.Text = reader.Item("ProductCode")
Des1.Text = reader.Item("Description")
Qty1.Text = reader.Item("Qty")
TextBox2.Text = reader.Item("Id")
Cmb2.Text = reader.Item("ProductCode")
Des2.Text = reader.Item("Description")
Qty2.Text = reader.Item("Qty")
TextBox3.Text = reader.Item("Id")
Cmb3.Text = reader.Item("ProductCode")
Des3.Text = reader.Item("Description")
Qty3.Text = reader.Item("Qty")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I am new to vb coding just want to help with displaying multiple rows on multiple textboxes. Above code picks up Payroll Id from a textbox from another table and then it goes through dbo.Smline table below. I want to display the multiple records under the same payroll Id in different textboxes. This code doesn't seem to be working properly.
On your form you have three set of controls. Thus, you are able to display just up to three products for each clicked Payroll_id. Your code inserts the same value in all sets. Change your code to the following:
Private Sub Line_Change2()
ResetControls()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Using cn
cn.Open()
Dim cmd As New SqlClient.SqlCommand
Dim reader As SqlClient.SqlDataReader
Try
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim counter as Integer = 1
While reader.Read
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Id").ToString()
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = reader.Item("ProductCode").ToString()
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Description").ToString()
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Qty").ToString()
counter += 1
if counter =3 then Exit While
End While
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Public Sub ResetControls()
For counter = 1 to 3
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = ""
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = ""
Next
End Sub
The above code exits the reading when it has more than three products for a Payroll_id, because you just have three sets of controls. But if you could have more than three products for each clicked Payroll_id and you want to display all of them, then you have to build your controls dynamically.

retrieving an autonumumber primary key field

I've this function to retrieve employee details in my Employees table. I am using vb.net 2012 and MS Access for my database. My problem is how to retrieve employee details using their ID's with an autonumber and primary key attributes/datatype? here's my code:
Public Sub DisplayEmployeeDetail()
Try
sqlEmployeeInfo = "SELECT * FROM tblEmployees WHERE tblEmployees.ID = " + txtDTRidnum.Text + ";"
Dim da As OleDb.OleDbDataAdapter = New OleDbDataAdapter(sqlEmployeeInfo, con)
Dim ds As New DataSet
da.Fill(ds, "tblEmployees")
Dim temp = ds.Tables("tblEmployees").Rows.Count
For i = 0 To temp - 1
lblFname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("FirstName"))
lblLname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("LastName"))
lblMname.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("MiddleName"))
lblAddress.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("Address"))
lblPosition.Text = CStr(ds.Tables("tblEmployees").Rows(i).Item("Position"))
Next
Catch ex As Exception
MessageBox.Show("Error in load: " & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
it gives System.Data.OleDb.Exception: Syntax error (missing operator) in query expression 'tblEmployees.ID='
use single quotes like this:
sqlEmployeeInfo = "SELECT * FROM tblEmployees WHERE tblEmployees.ID = '" + txtDTRidnum.Text + "';"
Additional you can try this even you don't want to use:
Private Sub getData()
Dim empDA As OleDbDataAdapter = New OleDbDataAdapter()
Dim empDS As DataSet = New DataSet
Dim empTable As DataTable = New DataTable("EMPLOYEES")
Dim adoConn As ADODB.Connection = New ADODB.Connection()
Dim adoRS As ADODB.Recordset = New ADODB.Recordset()
Try
empTable.Columns.Add("FirstName", Type.GetType("System.String"))
empTable.Columns.Add("LastName", Type.GetType("System.String"))
empTable.Columns.Add("MiddleName", Type.GetType("System.String"))
empTable.Columns.Add("Address", Type.GetType("System.String"))
empTable.Columns.Add("Position", Type.GetType("System.String"))
empDS.Tables.Add(empTable)
'Use ADO objects from ADO library (msado15.dll) imported
' as .NET library ADODB.dll using TlbImp.exe
'Specify your connection string here
adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;", "", "", -1)
adoRS.Open("SELECT * FROM tblEmployees WHERE tblEmployees.ID = " + txtDTRidnum.Text + ";", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1)
empDA.Fill(empTable, adoRS)
Dim temp = empTable.Rows.Count
For i = 0 To temp - 1
lblFname.Text = CStr(empTable.Rows(i).Item("FirstName"))
lblLname.Text = CStr(empTable.Rows(i).Item("LastName"))
lblMname.Text = CStr(empTable.Rows(i).Item("MiddleName"))
lblAddress.Text = CStr(empTable.Rows(i).Item("Address"))
lblPosition.Text = CStr(empTable.Rows(i).Item("Position"))
Next
adoRS.Close()
adoConn.Close()
Catch ex As Exception
MessageBox.Show("Error in load: " & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
adoRS.Close()
adoConn.Close()
End Try
End Sub
This Example Here
This error occurs because the text field txtDTRidnum.Text is empty.

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

How do I catch an SQL exception in a VB.NET 2010 code?

Okay, I am building a VB.NET system but I'm having troubles in catching an SQL exception in some parts of my code. In short, I am using a SELECT sql query to retrieve a particular record and I want to determine whether a record exist in a MSAccess database so that I don't retrieve 0 rows. 0 rows will lead to an exception during printing to a TextField. The following is a sample code I'm working on:
If txSearch.Text = "" Then
MsgBox("Please type the user id or use the barcode reader to scan", MsgBoxStyle.OkOnly, "Search Field Empty")
End If
'ElseIf txSearch.Text != "" Then
If txSearch.Text <> "" Then
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim dt As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim de As OleDb.OleDbDataAdapter
Dim sql As String
Dim sql1 As String
Dim temp_num As Integer
Dim cmd As New OleDb.OleDbCommand
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = new.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim search As String
search = txSearch.Text
MessageBox.Show("You are going to search for " + search + ". Click OK to continue.")
sql = "SELECT * FROM Student_Details WHERE Admin_No = '" & txSearch.Text & "'"
sql1 = "SELECT * FROM Laptop_Details WHERE Admin_No = '" & txSearch.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
de = New OleDb.OleDbDataAdapter(sql1, con)
'Dim check As Integer = sql.
'If check > 0 Then
'da.SelectCommand = cmd
ds = New DataSet("Student_Details")
da.Fill(ds, "Student_Details")
dt = New DataSet("Laptop_Details")
de.Fill(dt, "Laptop_Details")
'con.Close()
'If sql <> "" And sql1 <> "" Then
'If ds.Equals(1) And ds.Equals(1) Then
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
Dim com As New OleDb.OleDbCommand(sql, con)
Dim com1 As New OleDb.OleDbCommand(sql1, con)
Try
temp_num = com.ExecuteNonQuery
temp_num = com1.ExecuteNonQuery
Catch ex As IndexOutOfRangeException
Trace.WriteLine(ex.ToString)
End Try
con.Close()
'End If
'End If
End If
Try something like this:
if ds.Tables("Student_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
End if
if ds.Tables("Laptop_Details").Rows.Count > 0
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
End if
To help you with your comment I would do it like that:
if ds.Tables("Student_Details").Rows.Count > 0 And ds.Tables("Laptop_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
else
MsgBox("The user with id "+txSearch.Text+" does not exist")
end if
Try to use try-catch statement:
Try
Your code here for your query statements.
Catch ex as Exception MsgBox(ex.Message)End Try