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

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.

Related

Availability using Access Database

I am attempting to make a hotel booking system. However the availability has got me a bit confused. I have about 15 buttons which I am able to save the number to the database but when the form loads/ date changed. I need the button to stay red and be unclickable. For example if I had a room 11 booked from 3/06/17 to 5/06/17 then I'd need the button to remain red from the 3/06/17 to 4/06/17 since the room is able to still be booked on the 5/06/17 after cleaning. I hope this makes sense. Below is the code I am using to try to do this. The code does run however the button does not turn red.
I was thinking does my SQL statement need to be changed but I'm not too sure. I'm pretty new to coding so an explanation would be helpful. Thanks.
Private Sub ReadRecords()
Dim btn As Button = Nothing
Dim BookingFound As Boolean = False
Using MyConn As New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
Dim check As String = "SELECT COUNT(*) FROM [BookingInformation] WHERE [Date In] = '" & dtpDateIn.Value.Date & "' AND [Date Out] = '" & dtpDateOut.Value.Date & "'"
Dim BookingExists As Boolean = False
Dim command As OleDbCommand = New OleDbCommand(check, MyConn)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
If reader(0) = 0 Then
BookingExists = False
Else
BookingExists = True
End If
End While
End Using
If BookingExists = True Then
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
Dim command2 As OleDbCommand = New OleDbCommand(getData, MyConn)
Using reader As OleDbDataReader = command2.ExecuteReader()
While reader.Read()
BookingFound = True
strDateIn = reader("Date In").ToString()
strDateOut = reader("DateOut").ToString
strRoomNumber = reader("Room Number").ToString
End While
If BookingFound = True Then
btn.BackColor = Color.Red
End If
End Using
End If
MyConn.Close()
End Using
End Sub
Private Sub Room_Booking_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadRecords()
End Sub
You should make your access database understand your input as date, access database is very sensitive to datatypes, for example if you write
"SELECT * FROM [user_tb] WHERE user_id=1"
Your code will work fine if your user_id data type is autonumber.
so try
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = #" & dtpDateOut.Text & "#"
Instead of
Dim getData As String = "SELECT * FROM [BookingInformation] WHERE [Date Out] = '" & dtpDateOut.Text & "'"
That is replace ' with #

LogIn form with user and admin using VB.net and Mysql

I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID

Cannot open any more tables - OleDbException was unhandled

Good Day,
My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.
My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception
Thanks in advance for your time on answering my question.
here is my code for more detailed overview of my program,
Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
If shrdcon.con.State = ConnectionState.Closed Then
shrdcon.con.Open()
End If
Dim RoomNum As Integer
dtARoom.Clear()
Dim stoploop As Boolean
Dim count As Integer = 0
Dim rm1 As String
RoomAssign = ""
rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
dat.Fill(ds, "ARoom")
stoploop = False
count = 0
Do Until stoploop = "True"
RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)
ScheduleGeneration()
If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then
RoomA = RoomAssign
GenerateOfferingID()
Dim cmd1 As New OleDbCommand()
cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
cmd1.Connection = shrdcon.con
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
pipz.ExecuteNonQuery()
pipz.Dispose()
stoploop = True
Else
stoploop = False
End If
If stoploop = False Then
If count = 30 Then
stoploop = True
Else
count = count + 1
End If
End If
Loop
End Sub
This is typical error happens with Microsoft Jet engine when You have exceeded the maximum number of open TableIDs allowed by the Microsoft Jet database engine, which is 2048 with Jet3.5 engine and 1024 with older engines.
Even though you are closing the Command objects after each use, you are still using the same connection for the whole process, which actually holds the TableID's and is at some point of time exceeding the number of allowed open TableID's.
A probable solution would be to update the Jet Engine with the latest, which is available here
It might solve your problem, but if you are already using the latest engine, you have to look into other options to reduce the number of DB operations.
Try using the UpdateBatch method for applying the updates as a batch.
Hope this helps
Private Sub Command1_Click()
Dim myConnection As ADODB.Connection
Dim rsData As ADODB.Recordset
Set myConnection = New ADODB.Connection
myConnection.ConnectionString = "xxxxxxxxxxxxxxxxxxxx"
myConnection.Open
Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseClient
rsData.Open "select * from mytable", myConnection, adOpenStatic, adLockBatchOptimistic
For i = 1 To 10000
rsData.AddNew
rsData.Fields(0).Value = 1
rsData.Fields(1).Value = 2
Next i
rsData.UpdateBatch
rsData.Close
myConnection.Close
Set rsData = Nothing
End Sub
Good Evening,
Recently I encounter this type of error and i was able to resolve it by adding
con.close and call conState (a procedure conState- check below) before any insert/update or select statement
In my code i have something like
For i = 0 To DataGridView1.RowCount - 1
reg = DataGridView1.Rows(i).Cells(0).Value
Label2.Text = reg
'i added this two lines
***con.Close()***
***Call conState()***
Dim cmdcheck As New OleDbCommand("Select * from [2015/2016 UG CRF] where regno ='" & reg & "'", con)
Dim drcheck As OleDbDataReader
drcheck = cmdcheck.ExecuteReader
If drcheck.Read = True Then
GoTo A
End If
coursesFirst = String.Empty
coursesSecond = String.Empty
creditFirst = 0
creditSecond = 0
Dim cmdlevel As New OleDbCommand("Select * from [2015/2016 UG registration Biodata 5 april 16] where regno ='" & reg & "'", con)
Dim drlevel As OleDbDataReader
drlevel = cmdlevel.ExecuteReader
If drlevel.Read = True Then
level = drlevel.Item("level").ToString
faculty = drlevel.Item("faculty").ToString
program = drlevel.Item("programme").ToString
End If
...............
next
The conState is a connection testing if connection is closed is should open it again like in below
Public Sub conState()
If con.State = ConnectionState.Closed Then
con.Open()
End If
End Sub
This stop the error message
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:
OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;

Report only shows the last record

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

Change textbox value dynamically?

I have 7 textboxes named lblSun, lblMon etc and 7 buttons named cmdSun, cmdMon etc. I want to change the Text value of these text boxes and buttons from within the query. I've tried Me.Controls("cmd" & daysOfWeek(i)).Text, but it does not work.
The error is Object reference not set to an instance of an object.
Here is my code:
Public Sub loadSchedule()
' days of week
Dim daysOfWeek(0 To 6) As String
Dim i As Integer
Dim var As String
Dim ctrl As Control
' set up the days of the week
daysOfWeek(0) = "Sun"
daysOfWeek(1) = "Mon"
daysOfWeek(2) = "Tue"
daysOfWeek(3) = "Wed"
daysOfWeek(4) = "Thu"
daysOfWeek(5) = "Fri"
daysOfWeek(6) = "Sat"
' connect to the db
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection(Form1.conString)
con.Open()
' query stuff
Dim query As String
Dim cmd As New OleDb.OleDbCommand
Dim rs As OleDb.OleDbDataReader
' loop
For i = LBound(daysOfWeek) To UBound(daysOfWeek)
' set query
query = "SELECT * FROM Schedule WHERE Employee=" & employee & " AND ScheduleDay='" & daysOfWeek(i) & "'"
cmd = New OleDb.OleDbCommand(query, con)
rs = cmd.ExecuteReader()
' var
var = "cmd" & daysOfWeek(i)
' any results?
If rs.HasRows = True Then
' get it
rs.Read()
' show it baby
'Controls("lbl" & daysOfWeek(i)).Text = rs.Item("TimeIn") & " - " & rs.Item("TimeOut")
Me.Controls("cmd" & daysOfWeek(i) & "").Text = "Edit"
Else
' show it baby
Controls("lbl" & daysOfWeek(i)).Text = "RDO"
Controls("cmd" & daysOfWeek(i)).Text = "New"
End If
Next
' close db
con.Close()
End Sub
Can anyone help me? What am I doing wrong?
You are trying to access the controls in Me.Controls which don't exist, because the buttons/textboxes are inside a table.
You should use :
table.Controls("cmd" & daysOfWeek(i)).Text = "Edit"