Report only shows the last record - vb.net

I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.

It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report

Related

how to call checkbox value from sql to display on form vb.net

am doing this but not working only apply in first record its working in insert and update
i stored in sql as true or false
Sub db_load()
On Error Resume Next
Dim pringdata As String = "SELECT custcode_" & _
",custname_" & _
",custname2_" & _
",phone_" & _
",mobile_" & _
",custadd_" & _
",date_" & _
",cutomerzone_ " & _
",check_ " & _
" FROM custInfo "
Dim sqlconload As New SqlConnection(sqlcon)
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "custInfo")
For i As Integer = ds.Tables(0).Rows.Count = 0 To -1
If ds.Tables(0).Rows(i).Item("check_") = "true" Then
checkActive.Checked = True
Else
checkActive.Checked = False
End If
Next
sqlconload.Close()
I gather you are referring to a specific customer since you're only setting a single checkbox? You'll need to modify your query to match that.
Next, examine how you're storing the "check" column. In most cases, converting to Bool will resolve it but you may have to special case it based on available values.
Also, if the field you're looking at could be null, you'll have to account for that as well.
Here's a good pattern to follow that properly disposes of resources such as connections, commands, and readers.
Public Sub db_load()
Using cn = New SqlConnection(sqlcon)
cn.Open()
Using cmd = New SqlCommand("SELECT custcode,custname,custname2,phone,mobile,custadddate,customerzone,check FROM custInfo", cn)
Using dr = cmd.ExecuteReader()
If dr.Read Then
checkActive.Checked = CBool(dr("check"))
End If
End Using
End Using
End Using
End Sub

ODBC - unable to allocate an environment handle

Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.

Vb.net with access database: How can you help me simplify these codes?

this is my code:
'Set up connection string
Dim cnString As String
cnString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\testingDB.mdb"
Dim sqlQRY As String = "SELECT * " & _
"FROM users " & _
"WHERE firstName = '" & TextBox1.Text & "' " & _
" AND lastName = '" & TextBox2.Text & "'"
'Create connection
Dim conn As OleDbConnection = New OleDbConnection(cnString)
Try
' Open connection
conn.Open()
'create data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlQRY, conn)
'create dataset
Dim ds As DataSet = New DataSet
'fill dataset
da.Fill(ds, "user")
'get data table
Dim dt As DataTable = ds.Tables("user")
'display data
Dim row As DataRow
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 10 Then
MsgBox("10")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 9 Then
MsgBox("9")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) Then
MsgBox("SUCCESS")
Else
MsgBox("fail")
End If
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
' Close connection
conn.Close()
End Try
I'm trying it to make it simple with the same results. As you can see the if-else statements were messy but it works 100%. I do want the if-else statements to be simple and works the same as above.
Edited to check value of row(5) for DbNull values
try this for if-else statements:
Dim row As DataRow = dt.Rows(0)
Dim r5 as Object = row(5)
If IsDbNull(r5) then r5 = 0
If TextBox1.Text = row(1) And TextBox2.Text = row(2) Then
Select Case r5
Case 10, 9 : MsgBox(r5)
Case Else : MsgBox("SUCCESS")
End Select
Else
MsgBox("fail")
End If
Dim cmd as New OledbCommand
Dim sqlQRY As String = "SELECT count(*) " & _
"FROM users " & _
"WHERE firstName = #fname " & _
" AND lastName = #lname"
cmd.parameters.add("#fname",TextBox1.Text)
cmd.parameters.add("#lname",TextBox2.Text)
Dim Cnt as Integer
cmd = new oledbcommand(sqlQRy,con)
Cnt = Convert.ToInt32( cmd.ExecuteScalar())
if Cnt>=1 then
msgbox("Success")
else if
msgbox("Failure")
end if
You must be aware that your SQL could logically return more than 1 row. You need to make sure that when you read data that you intend to test in this way, that your SQL uses a primary key and return 1 row only otherwise, problems could happen when more data is added. I suggest you first ensure that exactly 1 row is returned before you perform your if test (see my comment to #SenthilKumar). You need to send appropriate message to user when no rows are found and not perform the test.
If you get exactly 1 row back, you have to ensure that the data is not null (if applicable, this depends on how your columns are defined).
Remember that data that comes form UI could be padded with blanks or be in mixed case. You may need to watch for this.
Your IF statement is not too complex as is.I am not sure what you are testing exactly, but one can observe that you are using the following conditions:
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
You can see that the the expression
dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) is common. You can assign the value to a Boolean expression and use it in your test.
You also should not include non-database processing in the scope of your try.
Just more little simpler ..
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
MsgBox("SUCCESS - " & format(dt.Rows(0).Item(5)))
Else
MsgBox("fail")
End If

vb.net check if function don't return anything

I have a vb.net function is which I am doing some thing which is returning a gridview to send it in email.Problem is that when I call the function in email then email is sent even there is nothing returned by function. I don't to send blank email at all. I want to when function return nothing then it shouldn't send email. Here is My function
Public Function emaildata(ByVal grdv As GridView, ByVal chk As String, ByVal celpos As Integer) As GridView
Dim comm As OleDbCommand = New OleDbCommand()
Dim bpv As String = ""
Dim gv As New GridView
For Each gvrow As GridViewRow In grdv.Rows
Try
Dim rdobtn As RadioButtonList = CType(gvrow.FindControl(chk), RadioButtonList)
If rdobtn.SelectedValue.Equals("5") Or rdobtn.SelectedValue.Equals("1") Or rdobtn.SelectedValue.Equals("6") Or rdobtn.SelectedValue.Equals("4") Or rdobtn.SelectedValue.Equals("2") Then
If bpv <> "" Then
bpv += ","
End If
bpv += gvrow.Cells(celpos).Text
comm.CommandText = "SELECT row_number() over(order by rownum) Sr, to_char(chq_num) Cheque#,to_char(bpv_amt,'9,999,999,999') Amount,vch_nar Narration,bnf_nam PartyName,acc_des Bank from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "') union all SELECT null,'Total :',to_char(sum(bpv_amt),'9,999,999,999') Amount,null,null,null from CHECK_DATA where bpv_num in(" & bpv.ToString() & ") and BPV_DTE=to_date('" & TreeView2.SelectedValue & "')"
comm.CommandType = CommandType.Text
comm.Connection = con
Dim da As New OleDbDataAdapter(comm)
Dim ds As New DataSet
da.Fill(ds)
gv.DataSource = ds
gv.DataBind()
End If
Catch ex As Exception
Response.Write("There is Problem In Cheque Approval System Please Contact With IT")
End Try
Next
Return gv
End Function
And I Call this in email function as a subject like this
email("malik.adeel#shakarganj.com.pk", "[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4), gridhtm(emaildata(GridView5, "chkStatusGM", 4)))
How can I do this that if emaildata(GridView5, "chkStatusGM", 4) returning nothing email shouldn't be sent?
Probably the easiest is to check if the GridView contains GridViewRows with the Count property:
Dim grdEmail = emaildata(GridView5, "chkStatusGM", 4)
If grdEmail.Rows.Count > 0
email("malik.adeel#shakarganj.com.pk",
"[Cheque Approval] GM Finance Reviewed (" & TreeView2.SelectedValue & ")" & subsmcnt(GridView5, "chkStatusGM", 4),
gridhtm(grdEmail))
End If

too slow in show report in vb.net 2010 using crytal report

I am using this code to show the report
Dim rpt As New CrystalReport1()
Dim sql As String
Dim where As String
If con Is Nothing OrElse con.State = ConnectionState.Closed Then
'MsgBox("closed")
OpenCon()
End If
Dim m As String
m = ""
For Each n As TreeNode In GetCheck(TreeView1.Nodes)
If n.Tag = 1 Then
m = m
Else
If m = "" Then
m = (n.Tag)
Else
m = m & ", " & (n.Tag)
End If
End If
Next
sql = "SELECT [bran_id],[f01],[f02],[f03],[f04],[f05],[f06],[f07],[f08],[bran_name],[comp_id],[comp_name],'" & dtStart.Value.Date & "' AS start_date, '" & dtEnd.Value.Date & "' AS end_date FROM [v_complain]"
If m = "" Then
MsgBox("لم يتم تحديد اى مدينة من فضلك قم بالاختيار اولا")
Exit Sub
Else
where = " WHERE bran_id in (" & m & ") and f02 between CONVERT(date,'" & dtStart.Value.Date & "',103) and CONVERT(date,'" & dtEnd.Value.Date & "',103)"
sql = sql + where
If cbF06.Checked = True Then
where = " AND (f06 like N'') or (f06 is null)"
sql = sql + where
End If
If cbF07.Checked = True Then
where = " AND (f07 like N'') or (f07 is null)"
sql = sql + where
End If
Dim dscmd As New SqlDataAdapter(sql, con)
Dim ds As New DataTable
dscmd.Fill(ds)
rpt.SetDataSource(ds)
CrystalReportViewer1.ReportSource = rpt
CrystalReportViewer1.Refresh()
End If
con.Close()
but it's too slow to show the report in the first time. When I try to run it again without closing the window it work perfectly. Is there any way to make it faster?
Thanks
How slow it is? Several seconds?
I believe it happens do to a need to initialize underling reports 'engine'. I had similar issues and the best I could come up with was to display "Creating report, please wait..." message to a user so they. As an alternative, when you start your app, you can make a 'fake' call to create a dummy report in the background without displaying anything to a user so all required resources will be initialized by the time user is ready to create a real report.