How can I change the value of an item in a list box while keeping the items display the same? - sql

I have a ListBox that gets populated with a SqlDataReader object and it looks great but the problem I'm running into is I want the data text field to display the data from the date field of the SQL query and have the data value of the ListBox to be from the url field. This is very easy to do if you use the Query Builder function within Visual Studio 2010. You just click on the ListBox and change the properties in the right hand properties column. However, since I didn't use the query builder function and I am coding it by hand, I cannot figure out for the life of me how to change the data text field of the list box to the date field and the data value field to the url field.
The logic behind this is that the user will be able to click on the date of their item, click the button, and it will navigate to the url that is provided in the SQL Database.
Here is the code I am using in the button click action;
Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SearchButton.Click
Dim startDate As Date
Dim endDate As Date
Dim connectionString As String
startDate = TextStartDate.Text
endDate = TextEndDate.Text
connectionString = SqlDataSource1.ConnectionString.ToString
Dim sqlConnection1 As New SqlConnection(connectionString)
Using sqlConnection1
Dim command As SqlCommand = New SqlCommand( _
"SELECT first_name, last_name, date, url FROM tbl_paystubs WHERE date>='" + startDate.ToString + "' AND date<='" + endDate.ToString + "';", _
sqlConnection1)
sqlConnection1.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read
SearchListBox.Items.Add(reader.Item("url"))
End While
reader.Close()
End Using
sqlConnection1.Close()
End Sub
Here are some pictures to help illustrate as well.
EDIT: I think I made this question a little hard to understand so I am going to clarify a little. Inside of the ListBox, the items that are there are now showing the Date when the search is completed, my question is, how can I make the "Open" button open a browser window with the ListBoxItems corresponding URL field?

you could create a little class like this:
internal class LbItem
{
internal string url;
internal string data;
public override string ToString()
{
return this.data;
}
}
and add instances of this class to your ListBox.Items:
listBox1.Items.Add(new LbItem { url = "http:xyz", data = "123" });
the listbox will show the LbItems as returned by the overridden ToString() function ...

I changed the code to the following which answered my question!
Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SearchButton.Click
Dim startDate As Date
Dim endDate As Date
startDate = TextStartDate.Text
endDate = TextEndDate.Text
Dim connectionString As String
startDate = TextStartDate.Text
endDate = TextEndDate.Text
connectionString = SearchDataSource.ConnectionString.ToString
Dim sqlConnection1 As New SqlConnection(connectionString)
Using sqlConnection1
Dim command As SqlCommand = New SqlCommand( _
"SELECT first_name, last_name, date, url FROM tbl_paystubs WHERE date>='" + startDate.ToString + "' AND date<='" + endDate.ToString + "';", _
sqlConnection1)
sqlConnection1.Open()
Dim da As New SqlDataAdapter(command)
Dim ds As New DataSet()
da.Fill(ds)
sqlConnection1.Close()
SearchListBox.DataSource = ds
SearchListBox.DataTextField = "date"
SearchListBox.DataValueField = "url"
SearchListBox.DataBind()
End Using
TextStartDate.Text = ""
TextEndDate.Text = ""
End Sub

Related

How to read date and time from database and compare it to the system date and time

I am working on a project using vb and one of my forms has to display the current active reminders (reminders that haven't hit their deadline yet) into a datagridview and I have another datagridview for reminders that are past the deadline. The date and time along with reminder information is saved into my access database and I want to read the date and time from database and compare it to the system date and time and then display the reminder information.
This is how my form looks like; the top datagridview is for current reminders and the bottom one is for past/out of date reminders:
This the code for my form and what I’ve tried:
Imports System.Data.OleDb
Public Class frmReminderInfo
Private Sub frmReminderInfo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DisplayCurrentReminders()
End Sub
Private Sub DisplayCurrentReminders()
Dim ReminderDateTime As Date
Dim CurrentDateTime As Date
CurrentDateTime = Date.Now
CurrentDateTime = FormatDateTime(Date.Now, DateFormat.GeneralDate)
ReminderDateTime = FormatDateTime(ReminderDateTime, DateFormat.GeneralDate)
If DbConnect() Then
DgvCurrentReminders.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "SELECT ReminderDate FROM TblReminder "
Dim rs As OleDbDataReader = .ExecuteReader()
While rs.Read
ReminderDateTime = (rs(0).ToString)
End While
End With
End If
cn.Close()
If CurrentDateTime = ReminderDateTime Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
Dim rs As OleDbDataReader = .ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvCurrentReminders)
NewStockRow.SetValues({rs("ReminderID"), rs("CustomerName"), rs("DeviceInfo"), rs("RepairPrice"), rs("ReminderDate")})
NewStockRow.Tag = rs("ReminderID")
DgvCurrentReminders.Rows.Add(NewStockRow)
End While
rs.Close()
End With
End If
cn.Close()
End Sub
End Class
Disposable database objects like Connection should be declared locally in the method where they are used in a Using block.
You don't seem to have any idea of what the parts of an Sql string mean. The Select portion list the fields you want to retrieve. A star (*) in this clause means select all the fields. Here we are using a Where clause to filter the records. Only records where the field ReminderDate is greater than or equal to a parameter will be returned. This will only work if the data has been inserted properly as a DateTime.
The While loop keeps overwriting the value of ReminderDateTime on each iteration so only the last value returned by the reader will remain. Also, you are trying to force a String into a variable declared as a Date. Won't work.
Assuming the code could get beyond If CurrentDateTime = ReminderDateTime Then you would be working with a closed connection. Commands can't execute on a closed connection.
You also don't seem to have an idea how class objects work. Dim SQLCmd As New OleDbCommand Here you declare a new instance of the Command. You have no connection and no CommandText so it can't possibly be executed.
Take a look at the following code until it starts to make sense. Look up what Using blocks do. Look up the Load method of a DataTable to see what it does. Check out what a DataSource property has to offer.
Private Sub frmReminderInfo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetCurrentReminders()
DgvCurrentReminders.DataSource = dt
End Sub
Private Function GetCurrentReminders() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
SQLCmd As New OleDbCommand("SELECT * FROM TblReminder Where ReminderDate >= #Date", cn)
SQLCmd.Parameters.Add("#Date", OleDbType.Date).Value = Now
cn.Open()
Using reader = SQLCmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function

Count guest reservation visual studio Ms access

I've been trying this for some time now,
So in my MS access database i have a
Table named "reservations" and inside the table are
Name(sid,jen)
Roomtype(single,double)
Arrivaldate(3/20/17, 3/20/17 )
Departuredate(3/21/17, 3/21/17)
And in my visual studio form i have
2 labels = lblsingle , lbldouble
1 button named btnok and
Datetimepicker named Datetimepicker1 (properties format set to "Short")
So here is my code:
Private sub Form1_Load
Dim time as DateTime = DateTime.Now
Dim format As String = "MM/d/yyyy"
Datetimepicker1.Text = time.ToString(format)
Private sub btnok_click
Con.open
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = " & Datetimepicker1.Text & " ",Con)
Dim dr As OleDbDataReader = cmb.ExecuteReader
Dim userfound As Boolean = False
While dr.Read
userfound = True
lblsingle.text = (dr(0).ToString())
End While
Con.Close()
End Sub
End Class
.
So what i want to happen is when i choose date 3/20/17 in my datetimepicker1. my lblsingle.text should count to "1" because in my database there is a single with the same date as my datetkmepicker1. But the result is "0"......... i really think there is something that makes my datetimepicker1 and the date in my ms access different,,
Please help.... do i need to change time format somewhere?
First your "Private sub btnok_click" will not handle the button click.
To handle "button click" your implementation should be as shown below (proto):
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
..
..
..
..
End Sub.
Coming to business logic:
When you want to update/increment your label?
Based on the description in your question, you want to update/increment the label as soon as your "DatTimePicker" value is changed.
But in code you are trying to do it in "Ok" button click.
If you want update the label, when you select a date from "datetimepicker", handle below event (proto):
Private Sub DateTimePicker1_ValueChanged(sender as Object, e as EventArgs) _
Handles DateTimePicker1.ValueChanged
..
..
..
..
End Sub
You must handle dates as datetime and not text:
Dim time as DateTime = DateTime.Today
Dim format As String = "yyyy'/'MM'/'/dd"
Datetimepicker1.Value = time
Private sub btnok_click
Con.open
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = #" & time.ToString(format) & "# ",Con)
Do not use text representations of date and time - use DateTime for all purposes except rendering output for your users (or serializing as text output like CSV files).
Handling DateTime values for your control
Use the .Value property to get and set your controls value:
Datetimepicker1.Value = DateTime.Now
Handling DateTime values for your database query
Use a (typed) parameter to pass DateTime values to your database query:
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = 'Single' AND [Arrivaldate] = ?", Con)
cmb.Parameters.Add(Datetimepicker1.Value)
OleDbCommand uses positional parameters - that means you need to match the order of your placeholders when adding parameters:
Dim roomtype As String
roomtype = "Single"
Dim cmb As new OleDbCommand("SELECT COUNT (*) FROM [reservations] WHERE [Roomtype] = ? AND [Arrivaldate] = ?", Con)
cmb.Parameters.Add(roomtype)
cmb.Parameters.Add(Datetimepicker1.Value)
Simplify retrieving scalar results like count(*)
If all you try to get is the count(*), you don't need a OleDbDataReader - let your command ExecuteScalar
lblsingle.Text = cmb.ExecuteScalar()

Take combobox SelectedIndex data and use in SELECT Query - VB.net

I'm a little desperate, hence why I'm here! I'm quite new to programming and have been given an assignment where I need to use a range of SQL queries to generate a simple HTML report table. There is also a user input, with them selecting the ClinicID from the comboBox and clicking a button to generate the report.
Basically, I have a comboBox that I have populated with 'ClinicID', as below. I have also made sure that SelectedIndex is working. I need to somehow use this in the SQL query method which I have also provided below.
Public Class frmReport1
'Set lsData for Clinics table
Dim lsData As List(Of Hashtable)
'On form load
Private Sub frmReport1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboClinicID.DropDownStyle = ComboBoxStyle.DropDownList
'Instantiate new ClinicController object
Dim cController As ClinicController = New ClinicController
'Load ClinicID
lsData = cController.findId()
For Each clinic In lsData
cboClinicID.Items.Add(CStr(clinic("ClinicID")))
Next
End Sub
'Selected Index
Private Sub cboClinicID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboClinicID.SelectedIndexChanged
Dim selectedIndex As Integer = cboClinicID.SelectedIndex
Dim selectedItem As Object = cboClinicID.SelectedItem
'Print in debug window
Debug.Print("Selected clinicID: " & selectedItem.ToString())
Debug.Print("Selected clinicID index: " & selectedIndex.ToString())
Dim htData = lsData.Item(selectedIndex)
End Sub
SQL query method - **note, I'm pulling from two different tables:
Where the '?' is, is where I assume I have to work in the 'SelectedItem' but I have no idea how!
Desired result: an html table outputted with these three selected fields.
Public Class ClinicOrderController
Public Const CONNECTION_STRING As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PharmDB.accdb"
'Dim cController As ClinicController = New ClinicController
'Dim oController As OrderController = New OrderController
Public Function findClinicOrder() As List(Of Hashtable)
'Instantiates a connection object
Dim oConnection As OleDbConnection = New OleDbConnection(CONNECTION_STRING)
'Instantiates a list of hashtables
Dim lsData As New List(Of Hashtable)
Try
Debug.Print("Connection string: " & oConnection.ConnectionString)
oConnection.Open()
Dim oCommand As OleDbCommand = New OleDbCommand
oCommand.Connection = oConnection
'Stored in the CommandText property of the command object
'SELECT SQL statement
oCommand.CommandText = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price FROM clinics, orders WHERE clinics.clinic_id = orders.clinic_id AND clinics.clinic_id = ? ORDER BY clinics.clinic_id"
'Compiles the prepared statement
'oCommand.Prepare()
'Executes the SQL statement and stores the results in data reader object
Dim oDataReader = oCommand.ExecuteReader()
'Process data set in Hashtable
Dim htTempData As Hashtable
Do While oDataReader.Read() = True
htTempData = New Hashtable
htTempData("ClinicID") = CStr(oDataReader("clinic_id"))
htTempData("DateOrdered") = CStr(oDataReader("date_ordered"))
htTempData("OrderTotalPrice") = CStr(oDataReader("total_price"))
lsData.Add(htTempData)
Loop
Debug.Print("The record was found.")
Catch ex As Exception
Debug.Print("ERROR:" & ex.Message)
MsgBox("An error occured!")
Finally
oConnection.Close()
End Try
'Return list of hashtables to the calling function
Return lsData
End Function
Really, really appreciate any help here. Ive been struggling with this for more than 8 hours (not joking - I give you permission to laugh)
If i understand you correctly, you want to use your dropdown selected item in your WHERE clause. To achieve that , revise your joining using INNER JOIN with ON then place your filtering in WHERE condition. Hope code below will help.
SELECT clinics.clinic_id,
, orders.date_ordered
, orders.total_price
FROM clinics INNER JOIN orders ON clinics.clinic_id = orders.clinic_id
WHERE clinics.clinic_id = selectedItem.ToString()
ORDER BY clinics.clinic_id
if the selectedItem.ToString() did not work, you can try SelectedValue
Assuming that clinic_id is a numeric field in the database: (otherwise just surround it with single quotes (''))
string clinicID = cboClinicID.SelectedItem.ToString();
string sql = string.Format(#"SELECT clinics.clinic_id, orders.date_ordered, orders.total_price
FROM clinics, orders
WHERE clinics.clinic_id = orders.clinic_id
AND clinics.clinic_id = {0}
ORDER BY clinics.clinic_id", clinicID);
oCommand.CommandText = sql;
You can also do it like this:
string sql = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price " +
"FROM clinics, orders " +
"WHERE clinics.clinic_id = orders.clinic_id " +
"AND clinics.clinic_id = " + clinicID + " " +
"ORDER BY clinics.clinic_id";
Please provide code in vb.net
Here is my code, I want to display prize amount from table where class id is condition :
If class id is 3 then prize for that is display in my textbox named txtprize.text and class Id is displayed in list box.
Private Sub listClassID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listClassID.SelectedIndexChanged
Dim classIdlist As String
classIdlist = New String(listClassID.SelectedItem.ToString)
Dim strSQL As String = "select [Prize Amount] from Master_Class WHERE [Class ID] =" & classIdlist
Dim dr As SqlDataReader
Try
con.Open()
cmd = New SqlCommand(strSQL, con)
dr = cmd.ExecuteReader()
If dr.Item(0) Then
txtPrize.Text = dr("[Prize Amount]").ToString
End If
dr.Close()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub

Update grid from a query

I have a Visual Basic 2010 application that uses a DataGridView to display a list of frequencies from a Microsoft Access 2010 database. The application uses the BindingNavigationPostionItem to allow navigation though the table.
The Move Next and Move Previous buttons move you up and down the list. The cool thing is, as you do this, I have code that sends the Frequency and Mode to my Yeasu radio and the radio then is set to that freq/mode.
This works great but, if I try to filter the DataGridView by the Service field, the ID field becomes blank and navigation does not work.
Here is the code that runs after you select what you want to filter by and you click the filter button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmbox1 As String
cmbox1 = ComboBox1.Text
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from HFUtil where service = '" & cmbox1 & "'", MyConn) '
da.Fill(ds, "HFUtil")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
BindingNavigator1.BindingSource = source1
DataGridView1.Refresh()
BindingNavigator1.Refresh()
'=========================================================
ListBox1.Items.Clear()
ListBox1.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ListBox1.Items.Add(sItemTemp)
Next
ComboBox2.Items.Clear()
ComboBox2.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ComboBox2.Items.Add(sItemTemp)
Next
End Sub
The only difference between this code and the code that runs on form load is - where clause in the data adapter.
What am I doing wrong?
I don't see in your code where you apply your filter. So, lets pretend for a second that you load your whole table into DataSet. Then next thing, you either use DataSet.DefaultView or create your custom DataView and assign this to DataSource property - you did this.
Now, all you have to do is apply row filter to the data view you use
view.RowFilter = "service = '" & cmbox1 & "'"
At this point you should only see subset of records and nothing should happen to your Id field. Because your data doesn't change.
I have suspicion, you changing your view somewhere and this is why you have problems.

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue