Printing Records from ODBC Connection - Stuck on First Page - vb.net

I am printing records from an ODBC connection but I am not able to print more than the first page. The code I have below generates multiple copies of the same first page. How can I iterate through my records and still create page breaks when necessary?
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
'MsgBox("Printing functionality is still under construction.", MsgBoxStyle.Information)
Dim RecordDoc As Drawing.Printing.PrintDocument
RecordDoc = New Drawing.Printing.PrintDocument
With RecordDoc.DefaultPageSettings
.Landscape = False
.Margins.Left = 50
.Margins.Right = 50
.Margins.Top = 50
.Margins.Bottom = 50
End With
RecordDoc.DocumentName = "Print Records"
AddHandler RecordDoc.PrintPage, AddressOf Me.printrecords
dlgPreview.Document = RecordDoc
dlgPreview.ShowDialog()
RecordDoc.Dispose()
End Sub
Private Sub PrintRecords(ByVal sender As Object, ByVal e As Drawing.Printing.PrintPageEventArgs)
Dim lvi As ListViewItem
Dim Conn As OdbcConnection
Dim Reader As OdbcDataReader
Dim strFname As String = ""
Dim strLname As String = ""
Dim strReportHdr As String = ""
Dim strMainCategory As String = ""
Dim strColumnHeader As String = ""
Dim intLinesPerPage As Integer = 0
Dim x, y As Single
Dim myfont As Font = New Font("Arial", 12, FontStyle.Regular)
Dim myPen As New Pen(Color.Black, 3)
'DEFINE THE REPORT HEADER BASED ON LISTVIEW SELECTIONS
'FIRST, GET THE COLUMN NUMBER SELECTED. YOU'LL USE THIS FOR THE REPORT HEADER AS WELL AS WHEN PRINTING DATA
Dim PrintColHeader As ColumnHeader = ListView1.Columns(intLViewColSort)
'REMOVE THE < OR > AS NECESSARY, IF PRESENT
If PrintColHeader.Text.StartsWith("> ") Then
strColumnHeader = Mid(PrintColHeader.Text, 3) & ", in descending order"
ElseIf PrintColHeader.Text.StartsWith("< ") Then
strColumnHeader = Mid(PrintColHeader.Text, 3) & ", in ascending order"
End If
If rdoCustInfo.Checked = True Then
strMainCategory = "Customer Information"
ElseIf rdoCustVendPrefs.Checked = True Then
strMainCategory = "Customer Vendor Preferences"
ElseIf rdoPricePts.Checked = True Then
strMainCategory = "Customer Price Points"
ElseIf rdoSalesHist.Checked = True Then
strMainCategory = "Customer Sales History"
ElseIf rdoSpecific.Checked = True Then
strMainCategory = "Other"
Else
MsgBox("System error with print function. Have a glass of wine.", MsgBoxStyle.Critical)
Exit Sub
End If
y = e.MarginBounds.Y
x = e.MarginBounds.X
e.Graphics.DrawRectangle(myPen, e.MarginBounds.X, e.MarginBounds.Y + 20, 500, 1)
e.Graphics.DrawString(strMainCategory & " - " & strColumnHeader, myfont, Brushes.Black, x, y)
y += CInt(2 * myfont.GetHeight(e.Graphics))
myfont = New Font("Arial", 10, FontStyle.Regular)
intLinesPerPage = e.MarginBounds.Height / myfont.GetHeight(e.Graphics)
'Open Connection TO ASC
Conn = New OdbcConnection(ConnString)
Conn.Open()
For Each lvi In ListView1.Items
'Execute Query
cmdString = "select lastname,firstname,street1,street2,city,state,zipcode,phonenum,emailaddress from customer where customernum=" & lvi.Text
Dim Cmd As New OdbcCommand(cmdString, Conn)
Reader = Cmd.ExecuteReader()
'Process The Result Set
While (Reader.Read())
Dim tempy As Integer
tempy = y
Dim CustName As String = Trim(Reader("firstname")) & " " & Trim(Reader("lastname"))
CustName = StrConv(CustName, VbStrConv.ProperCase)
e.Graphics.DrawString(CustName, myfont, Brushes.Black, e.MarginBounds.X, y)
y += CInt(myfont.GetHeight(e.Graphics))
Dim street As String = ""
If Trim(Reader("street2").ToString) <> "" And Not (IsDBNull(Reader("street2"))) Then
street += Trim(Reader("street1").ToString) & vbCrLf & Trim(Reader("street2"))
Else
street += Trim(Reader("street1").ToString)
End If
street = StrConv(street, VbStrConv.ProperCase)
e.Graphics.DrawString(street, myfont, Brushes.Black, e.MarginBounds.X, y)
y += CInt(myfont.GetHeight(e.Graphics))
Dim CityStateZip As String = ""
CityStateZip = StrConv(Trim(Reader("city")), VbStrConv.ProperCase) & ", " & Trim(Reader("state")) & ", " & Reader("zipcode")
e.Graphics.DrawString(CityStateZip, myfont, Brushes.Black, e.MarginBounds.X, y)
x += 200
e.Graphics.DrawString(Trim(Reader("phonenum")), myfont, Brushes.Black, x, tempy)
tempy += CInt(myfont.GetHeight(e.Graphics))
y += CInt(2 * myfont.GetHeight(e.Graphics))
e.Graphics.DrawString(Trim(Reader("emailaddress")), myfont, Brushes.Black, x, tempy)
x = e.MarginBounds.X
'If intPrintLineCount1 > intLinesPerPage Then
' e.HasMorePages = True
' intPrintLineCount1 = 0
'Else
' e.HasMorePages = False
'End If
If y + myfont.Height > e.MarginBounds.Bottom Then
e.HasMorePages = True
End If
'intPrintLineCount1 += 10
End While
Cmd.Dispose()
Next
Reader.Close()
Conn.Close()
Conn.Dispose()
End Sub

Related

How to auto display form Update in vb.net?

A part of a system I am creating has a kitchen display system but I dont get how to automatically display the contents in my form
Public Sub GetOrders()
Try
kitchenFlowLayoutPanel.Controls.Clear()
Dim i As Integer
Dim sql As String
sql = "SELECT c.cart_id, c.invoice_no, c.table_no, c.sale_time, f.item_name, c.serve_size, c.quantity FROM tbl_cart AS c INNER JOIN tbl_food AS f on f.item_id = c.items_id WHERE c.status='Pending'"
conn.Open()
cmd = New MySqlCommand(sql, conn)
cmd.ExecuteReader()
conn.Close()
Dim dTable1 As New DataTable()
Dim dAdaptor1 As New MySqlDataAdapter(cmd)
dAdaptor1.Fill(dTable1)
Dim panel1 As FlowLayoutPanel
Dim panel2 As FlowLayoutPanel
For i = 0 To dTable1.Rows.Count - 1
panel1 = New FlowLayoutPanel
panel1.AutoSize = True
panel1.Width = 260
panel1.Height = 500
panel1.FlowDirection = FlowDirection.TopDown
panel1.BorderStyle = BorderStyle.FixedSingle
panel1.Margin = New Padding(10, 10, 10, 10)
panel2 = New FlowLayoutPanel
panel2.BackColor = Color.FromArgb(50, 55, 89)
panel2.AutoSize = True
panel2.Width = 230
panel2.Height = 125
panel2.FlowDirection = FlowDirection.TopDown
panel2.Margin = New Padding(0, 0, 0, 0)
Dim label1 As New Label
label1.ForeColor = Color.White
label1.Margin = New Padding(10, 5, 3, 0)
label1.Font = New Font(label1.Font, FontStyle.Bold)
label1.AutoSize = True
Dim label2 As New Label
label2.ForeColor = Color.White
label2.Margin = New Padding(10, 5, 3, 0)
label2.AutoSize = True
Dim label3 As New Label
label3.ForeColor = Color.White
label3.Margin = New Padding(10, 5, 3, 0)
label3.AutoSize = True
Dim label4 As New Label
label4.ForeColor = Color.White
label4.Margin = New Padding(10, 5, 3, 0)
label4.AutoSize = True
Dim label5 As New Label
label5.ForeColor = Color.White
label5.Margin = New Padding(10, 5, 3, 0)
label5.AutoSize = True
label1.Text = "Entry ID : " & dTable1.Rows(i)("cart_id").ToString
label2.Text = "Invoice No : " & dTable1.Rows(i)("invoice_no").ToString
label3.Text = "Table No : " & dTable1.Rows(i)("table_no").ToString
label4.Text = "Order Time : " & dTable1.Rows(i)("sale_time").ToString
label5.Text = Environment.NewLine & "ORDERED ITEM : " & Environment.NewLine & Environment.NewLine & " Item : " & dTable1.Rows(i)("item_name").ToString & Environment.NewLine & " Serve Size : " & dTable1.Rows(i)("serve_size").ToString & Environment.NewLine & " Qty: " & dTable1.Rows(i)("quantity").ToString & Environment.NewLine & Environment.NewLine
panel2.Controls.Add(label1)
panel2.Controls.Add(label2)
panel2.Controls.Add(label3)
panel2.Controls.Add(label4)
panel2.Controls.Add(label5)
panel1.Controls.Add(panel2)
Dim btn As New Guna.UI2.WinForms.Guna2Button
btn.AutoRoundedCorners = True
btn.Size = New Size(100, 35)
btn.FillColor = Color.FromArgb(241, 85, 126)
btn.Margin = New Padding(60, 5, 3, 10)
btn.Location = New Point(0, 0)
btn.Text = "Complete"
btn.Tag = dTable1.Rows(i)("cart_id").ToString ' store id
AddHandler btn.Click, AddressOf btn_Click
panel2.Controls.Add(btn)
kitchenFlowLayoutPanel.Controls.Add(panel1)
Next
Catch ex As Exception
conn.Close()
MsgBox(ex.Message, vbCritical)
End Try
End Sub
I tried putting it in a do loop but it shows errors even before I can log in to the system.
I have also tried to use incorporate "GetOrders().refresh" but it was also not working.
It is difficult to understand what exactly you're trying to achieve.
In this example, a button named RefreshButton was added to the Form.
This shows your GetOrders method getting called from the ButtonClick event.
Private Sub GetOrders()
'your GetOrders code...
End Sub
Private Sub RefreshButton_Click(sender As Object, e As EventArgs) Handles RefreshButton.Click
Try
GetOrders() ' this will call your GetOrders method
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub

How to print datagridview data in horizontal line with printdocument?

I have a query in the SqlServer database, the result of that query is played inside a Datagridview, the result can contain from 0 to 100 data or even more if you doubt it.
I'm trying to print the "Identification" column of Datagridview horizontally, but without success. I have researched in several places and nothing too.
screenshot of form with DataGridView
Follow the form code:
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Drawing.Printing
Public Class frm_relatorio_entregas
' Variables used in the module
Dim RelatorioTitulo As String ' Report title
Dim paginaatual As Integer ' Page number being printed
Dim LinhaAtual As Integer ' Current line number being printed
Dim LinhasporPagina As Integer ' Number of lines per page
Dim PosicaoDaLinha As Single ' Position of the line being printed
Dim registro As Integer ' Record being printed
Private Sub Imprimir()
RelatorioTitulo = "Delivery Report"
Dim doc As PrintDocument = New PrintDocument
AddHandler doc.PrintPage, New Printing.PrintPageEventHandler(AddressOf Me.pdRelatorios_Printpage)
AddHandler doc.BeginPrint, New Printing.PrintEventHandler(AddressOf Me.Begin_Print)
Dim dialogo As PrintDialog = New PrintDialog
'dialogo.Document = doc
' If (dialogo.ShowDialog = DialogResult.OK) Then
Dim preview As PrintPreviewDialog = New PrintPreviewDialog()
preview.Document = doc
preview.WindowState = FormWindowState.Maximized
preview.PrintPreviewControl.Zoom = 1.0
preview.ShowDialog()
'End If
End Sub
Private Sub Begin_Print(ByVal sender As Object, ByVal e As Printing.PrintEventArgs)
' Assigning values ​​to variables at the start of printing
LinhaAtual = 0
paginaatual = 1
PosicaoDaLinha = 0
registro = 0
End Sub
Private Sub pdRelatorios_Printpage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
' Margin variables (e.MarginBounds obtain the rectangular area that represents the part of the page within the margins.)
Dim MargemEsquerda As Single = e.MarginBounds.Left
Dim MargemDireita As Single = e.MarginBounds.Right
Dim MargemSuperior As Single = e.MarginBounds.Top
Dim MargemInferios As Single = e.MarginBounds.Bottom
'Pen class defines an object used to define lines and curves
Dim CanetaDaImpressora As Pen = New Pen(Color.Black, 1)
'Variables of the fonts used (the font class defines a specific format for text, including font face, size and style attributes.
Dim FonteNegrito As Font
Dim FonteTitulo As Font
Dim FonteSubTitulo As Font
Dim FonteRodape As Font
Dim FonteNormal As Font
Dim font1 As Font
'Define effects on fonts used
FonteNegrito = New Font("Arial", 9, FontStyle.Bold)
FonteTitulo = New Font("Arial", 13, FontStyle.Bold)
FonteSubTitulo = New Font("Arial", 9, FontStyle.Bold)
FonteRodape = New Font("Arial", 8)
FonteNormal = New Font("Calibri", 9)
font1 = New Font("Segoe UI", 8, FontStyle.Bold)
'Print the title of the report
e.Graphics.DrawString(RelatorioTitulo, FonteTitulo, Brushes.Black, MargemEsquerda + 200, 30, New StringFormat)
If DateTimePicker1.Value = DateTimePicker1.Value Then
e.Graphics.DrawString(DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
Else
e.Graphics.DrawString(DateTimePicker1.Value & " - " & DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
End If
'Define the number of lines per page
LinhasporPagina = CInt(e.MarginBounds.Height / New Font("Calibri", 18).GetHeight(e.Graphics) - 2)
While (LinhaAtual <= LinhasporPagina AndAlso registro <= DataGridView1.Rows.Count - 1)
PosicaoDaLinha = MargemSuperior + (LinhaAtual * New Font("Calibri", 18).GetHeight(e.Graphics) + 30)
e.Graphics.DrawString(DataGridView1.Rows(registro).Cells(0).Value.ToString, New Font("Calibri", 8, FontStyle.Bold), Brushes.Black, 30, PosicaoDaLinha, New StringFormat())
'Increment record
registro += 1
'increment line
LinhaAtual += 1
End While
'baseboard
e.Graphics.DrawLine(CanetaDaImpressora, 20, MargemInferios + 15, 1150, MargemInferios + 15)
e.Graphics.DrawString(System.DateTime.Now.ToString(), FonteRodape, Brushes.Black, 30, MargemInferios + 15, New StringFormat())
e.Graphics.DrawString("Página : " & paginaatual, FonteRodape, Brushes.Black, 1070, MargemInferios + 15, New StringFormat)
'Increase the page number
paginaatual += 1
'Here check if you are going to open a new page
If (LinhaAtual > LinhasporPagina) Then
' When you open a new page, you have to reset LlinhaAtual
e.HasMorePages = True
LinhaAtual = 0
Else
e.HasMorePages = False
End If
End Sub
Private Sub frm_relatorio_entregas_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtcod.Clear()
txtrazao.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
ComboBox1.SelectedIndex = 0
txtcod.Select()
End Sub
Private Sub txtcod_KeyUp(sender As Object, e As KeyEventArgs) Handles txtcod.KeyUp
If e.KeyCode = Keys.F2 Then
frm_consulta_cliente_cadastro.ShowDialog()
End If
End Sub
Private Sub consulta()
DataGridView1.Rows.Clear()
Cursor.Current = Cursors.WaitCursor
Dim consultando As New frm_aguarde_consultando
consultando.Show()
' Set cursor as hourglass
Application.DoEvents()
Dim ano, mes, dia As Integer
Dim var1data, var2data As Date
Dim dinicio, dfim As String
var1data = DateTimePicker1.Value '.ToString.Substring(0, 10)
dia = var1data.Day
mes = var1data.Month
ano = var1data.Year
dinicio = ano & "-" & mes & "-" & dia
var2data = DateTimePicker2.Value
dia = var2data.Day
mes = var2data.Month
ano = var2data.Year
dfim = ano & "-" & mes & "-" & dia
Using sqlcoon As SqlConnection = GetConnectionsql()
Dim READER As SqlDataReader
Try
sqlcoon.Open()
Dim Query As String
Query = "select MOV_IDENTIFICACAO,MOV_PROTOCOLO,MOV_DATADOC,MOV_SITUACAO,MOV_DATAENTREGA,MOV_HORAENTREGA,MOV_SITEND_CODIGO
from movimento where MOV_DATADOC = '" & dinicio & "'
AND MOV_CLI_CODIGO = '" & txtcod.Text & "' AND MOV_SITUACAO = '" & "E" & "'
AND CAST(MOV_DATAENTREGA AS DATE) = '" & dfim & "' "
Dim COMMAND As SqlCommand = New SqlCommand(Query, sqlcoon)
READER = COMMAND.ExecuteReader
While READER.Read
Dim MOV_IDENTIFICACAO = READER("MOV_IDENTIFICACAO")
Dim MOV_DATADOC = READER("MOV_DATADOC")
Dim MOV_DATAENTREGA = READER("MOV_DATAENTREGA")
Dim MOV_PROTOCOLO = READER("MOV_PROTOCOLO")
Dim MOV_SITUACAO = READER("MOV_SITUACAO")
Dim MOV_SITEND_CODIGO = READER("MOV_SITEND_CODIGO")
DataGridView1.Rows.Add(MOV_IDENTIFICACAO, MOV_PROTOCOLO, MOV_DATADOC, MOV_SITUACAO, MOV_DATAENTREGA, MOV_SITEND_CODIGO)
End While
READER.Close()
sqlcoon.Close()
''--------------'''''''''
Label9.Text = DataGridView1.Rows.Count
For Each linha In DataGridView1.Rows
Dim altura As Integer = 17
linha.height = altura
Next
If DataGridView1.Rows.Count >= 0 Then
' Set cursor as default arrow
Cursor.Current = Cursors.Default
' Hide the please wait form
consultando.Hide()
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
' sqlcoon.Dispose()
End Try
sqlcoon.Open()
Try
For r As Integer = 0 To DataGridView1.Rows.Count - 1
Dim COMMAND3 As SqlCommand
Dim READER3 As SqlDataReader
Dim Query_3 As String
Query_3 = "select IMOV_CODIGORECBTO from imovimento where IMOV_MOV_IDENTIFICACAO ='" & DataGridView1.Rows(r).Cells(0).Value.ToString & "'"
COMMAND3 = New SqlCommand(Query_3, sqlcoon)
READER3 = COMMAND3.ExecuteReader
While READER3.Read
Dim IMOV_CODIGORECBTO = READER3("IMOV_CODIGORECBTO")
'DataGridView1.Columns(6).HeaderCell.Value = "ID"
DataGridView1.Rows(r).Cells(6).Value = IMOV_CODIGORECBTO
End While
READER3.Close()
Next
DataGridView1.Sort(DataGridView1.Columns(6), ListSortDirection.Ascending)
sqlcoon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
consulta()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Imprimir()
End Sub
End Class
screenshot of what is currently being printed
screenshot of I would like the result to be:
Would anyone have any ideas, tools or means to help me? I thank.
An alternative would be to:
Get just the column values that you want.
Join the values from #1 using a delimiter, such as a tab.
Use the Graphics.DrawString method (documentation) for the value from #2.
There will need to be some considerations:
You will need to measure the string from #3 to see if it exceeds the bounds of your print document
If so, then you will need to print multiple pages, picking up where you left off.
Update
Per the OP's request, here is an example. Keep in mind that it doesn't account for the considerations listed above. That will take a bit of effort in debugging to account for those points:
Private Sub pdRelatorios_PrintPage(sender As Object, e As PrintPageEventArgs) Handles pdRelatorios.PrintPage
Dim title = "Relatorio de Entregas"
Dim titleFont = New Font(Font.FontFamily, Convert.ToSingle(Font.Size * 1.5), FontStyle.Bold)
Dim titlePosition = New PointF(Convert.ToSingle(e.MarginBounds.X * 2 - e.PageBounds.Width / 2), e.MarginBounds.Y)
Dim titleSize = e.Graphics.MeasureString(title, titleFont)
e.Graphics.DrawString(title, titleFont, SystemBrushes.ControlText, titlePosition)
Dim cellValues = DataGridView1.Rows.Cast(Of DataGridViewRow).Select(Function(row) row.Cells(0)?.Value?.ToString())
Dim joinedCellValues = String.Join(Constants.vbTab, cellValues)
Dim bodyBounds = New RectangleF(e.MarginBounds.X, Convert.ToSingle(titleSize.Height + e.MarginBounds.Y), e.PageBounds.Width - e.MarginBounds.X * 2, e.PageBounds.Height - e.MarginBounds.Y * 2)
e.Graphics.DrawString(joinedCellValues, Font, SystemBrushes.ControlText, bodyBounds)
End Sub

Find and highlight the max value in from multiple column in VB.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error
maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

Operator '+' is not defined for type 'Decimal' and type 'DBNull'

im working to show the data in my datagrid,and show the total of items brought in textbox2,but this error "Operator '+' is not defined for type 'Decimal' and type 'DBNull'." what is the problem? please help me i need to finish this so badly. :(
Private Sub dailySales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Connect()
DataGridView1.DataSource = dtb
dtb.Columns.Add("Transaction Code")
dtb.Columns.Add("Transaction Date ")
dtb.Columns.Add("Item Code")
dtb.Columns.Add("Item")
dtb.Columns.Add("Description")
dtb.Columns.Add("Quantity")
dtb.Columns.Add("Price")
dtb.Columns.Add("Total")
display()
con.Close()
total()
TextBox1.Text = DataGridView1.RowCount()
Me.DataGridView1.DefaultCellStyle.Font = New Font("Cambria", 10)
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("Cambria", 12)
Me.DataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(129, 207, 224)
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
End Sub
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub
Sub display()
con.Connect()
Label6.Text = Date.Now.ToString("dd MMMM yyyy")
Dim da = Label6.Text
Dim sc = " where lower(tns_date) like lower('%" & da & "%') "
Dim sql = "select * from tns " & sc & " order by tns_code desc"
odr = con.Retrieve(sql)
dtb.Clear()
While (odr.Read)
Dim ic = odr.GetOracleValue(0)
Dim itn = odr.GetOracleValue(1)
Dim de = odr.GetOracleValue(2)
Dim ca = odr.GetOracleValue(3)
Dim pr = odr.GetOracleValue(4)
Dim st = odr.GetOracleValue(5)
Dim sst = odr.GetOracleValue(6)
dtb.Rows.Add(ic, itn, de, ca, pr, st, sst)
End While
con.Close()
End Sub
Test like this.
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
If Not isDBNull(DataGridView1.Rows(x).Cells(7).Value) then sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub

vb PrintDocument not printing within specified margins

I am using the following code to print but every time I print to a laser printer, the right and bottom margins get cut off regardless of what I set my margins at. Could anyone shed some light on this situation? Note, I have tried using PrintDoc.OriginAtMargins = True/False but it doesn't appear to be working either.
/code/
Public MarginSize As Integer = 15
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'temp = Nothing
'With dgView
' For Each row In dgView.Rows
' temp += row.Cells(0).Value & " " & row.Cells(1).Value & " " & row.Cells(2).Value & " " & row.Cells(3).Value & vbNewLine
' Next
'End With
PrintDialog.PrinterSettings = PrintDoc.PrinterSettings
If PrintDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDoc.PrinterSettings = PrintDialog.PrinterSettings
Dim PageSetup As New PageSettings
With PageSetup
.Margins.Left = MarginSize
.Margins.Right = MarginSize
.Margins.Top = MarginSize
.Margins.Bottom = MarginSize
.Landscape = False
End With
PrintDoc.DefaultPageSettings = PageSetup
End If
' PrintDoc.OriginAtMargins = False
PrintPreviewDialog.Document = PrintDoc
PrintPreviewDialog.WindowState = FormWindowState.Maximized
PrintPreviewDialog.PrintPreviewControl.Zoom = 1
PrintPreviewDialog.ShowDialog()
End Sub
Private Sub PrintDoc_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDoc.PrintPage
Static intStart As Integer
Dim fntText As Font = txtDrawnBy.Font
Dim txtHeight As Integer
Dim LeftMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Left
Dim RightMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Width - MarginSize
Dim TopMargin As Integer = PrintDoc.DefaultPageSettings.Margins.Top
Dim BottomMargin As Integer = PrintDoc.DefaultPageSettings.PaperSize.Height - MarginSize
txtHeight = PrintDoc.DefaultPageSettings.PaperSize.Height - PrintDoc.DefaultPageSettings.Margins.Top - PrintDoc.DefaultPageSettings.Margins.Bottom
Dim LinesPerPage As Integer = CInt(Math.Round(txtHeight / (fntText.Height + 0.025)))
'Draw Rectangle for Margin
e.Graphics.DrawRectangle(Pens.Red, e.MarginBounds)
Dim y1 As Integer = e.PageBounds.Height.ToString / 3
Dim y2 As Integer = e.PageBounds.Height.ToString / 3 * 2
'Draw line 1/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y1, RightMargin, y1)
'Draw line 3/4 way down
e.Graphics.DrawLine(Pens.Orange, LeftMargin, y2, RightMargin, y2)
Dim intLineNumber As Integer
Dim sf As New StringFormat
Dim LineStep As Integer = 0
For intCounter = intStart To 66
'Print line numbers
e.Graphics.DrawString(intLineNumber.ToString & ": ", fntText, Brushes.Black, LeftMargin, fntText.Height * intLineNumber + TopMargin)
intLineNumber += 1
If intLineNumber > LinesPerPage Then
intStart = intCounter
e.HasMorePages = True
Exit For
End If
Next
End Sub
I have also attached an image of my results.
Image of print results