Change textbox value dynamically? - vb.net

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"

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 #

Loop through databases get the value and put it in a specific place in datagridview

I have a DataGridView with 2 columns. The first column is populated with folder paths and the second column is empty. Inside each folder path is a single database named DB1. I would like to extract 1 value (VALUE) from each database and then put that value next to corresponding database path, in the second column. This is the query I am using
Select CODE, VALUE from DB1 where CODE = 2419
I know how to populate a DataGridView and how to extract 1 value from the database, but with this I don't even know where to begin.
EDIT
I've managed to create working loop but don't know how to add those values to corresponding places in datagridview.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
MsgBox(reader("VALUE"))
End While
End Using
End Using
End Using
Next
EDIT 2
With code above I get all values in msgbox. Only thing left is to insert another loop to put all those values (starting with row 0) to datagridview.
If I replace msgbox with
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (reader("VALUE"))
Next
then all rows are populated with only last value (value from last database).
EDIT 3
I've changed
value = reader.Read()
with
While (reader.Read())
value = reader("VALUE")
End While
I'm still not sure how your query works, but assuming it does, I've changed your code.
For Each row As DataGridViewRow In DataGridView1.Rows
Dim sendtroopid As String
sendtroopid = row.Cells("CODE").Value
On Error Resume Next
Dim FilePath As String = sendtroopid 'DATABASE PATH
Dim value as string = "" ' declare a string variable to hold the result
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT CODE, VALUE FROM DB1 WHERE CODE = #CODE", con)
cmd.Parameters.AddWithValue("#CODE", "2419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
value = reader.Read()
End Using
End Using
End Using
row.Cells(1) = value ' put it in the datagridview cell
Next
Fill it as the rows draw..
Protected Sub GridView1_RowDataBound(sender As Object, e As _
System.Web.UI.WebControls.GridViewRowEventArgs) Handles _
GridView1.RowDataBound
Dim DGRow As GridViewRow = sender
If DGRow.RowType = DataControlRowType.DataRow Then
Dim TestPath As String = DGRow.Cells(0).Text
Dim FoundKey As String = GetKeyFromOtherDatabase(TestPath)
DGRow.Cells(1).Text = FoundKey
End If
End Sub
Private Function GetKeyFromOtherDatabase(testpath) As String
Dim FoundKey As String = ""
' FoundKey = Double something magical...
Return FoundKey
End Function

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

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.

How to create different instances of a form

The below Code is written inside the Timer Tick event. It works fine as long as the Time and Date are not same. When the Time and Date are same it only displays 1 message. How can I show multiple message for the same date and Time ? I think this can be done If I create different instances for a form. But I don't know how many same time and Date will be there in the database. So I can't do that. Is there any work around ?
Dim frm As New frmMessage
Dim nowDate As String = String.Format("{0:M/d/yyyy}", DateTime.Now)
Dim nowTime As String = String.Format("{0:h:mm tt}", DateTime.Now)
Dim mySelectQuery As String = "SELECT ReminderID, Date, Time, Subject, Reminder FROM Reminder WHERE Date LIKE '" & nowDate & "' AND Time LIKE '" & nowTime & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Try
If sqReader.HasRows = True Then
While sqReader.Read()
frm.Show()
If (Not sqReader.IsDBNull(0)) Then
frm.txtID.Text = sqReader.GetInt32(0)
End If
If (Not sqReader.IsDBNull(1)) Then
frm.txtDate.Text = sqReader.GetString(1)
End If
If (Not sqReader.IsDBNull(2)) Then
frm.txtTime.Text = sqReader.GetString(2)
End If
If (Not sqReader.IsDBNull(3)) Then
frm.txtSubject.Text = sqReader.GetString(3)
End If
If (Not sqReader.IsDBNull(4)) Then
frm.txtReminderText.Text = sqReader.GetString(4)
End If
End While
End If
sqReader.Close()
sqConnection.Close()
Catch ex As Exception
MsgBox("Error:" & ex.Message, vbExclamation)
End Try
if i understood correctly , you want to show a form for each row retrunring from the database.
i`m not sure this sort of UI practice is best if you have more than a couple of rows ,
but you can instanciate a new form as you said for each row,
instead of using the same instance
all you need to do is replace:
frm.Show()
with
Dim newForm As New frmMessage()
newForm.Show()