Count guest reservation visual studio Ms access - vb.net

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()

Related

How i can get max value with a condition in within datatable VB.NT

I have datatable named (Dt)
Has 2 column ("Type","value").
How i can get max value where tybe = textbox1.text ____
in (datatable)ADO.net not SQL server
Thank you
Ok, so lets assume two buttons.
First button to load the data table form SQL server
(that you suggest/note you already have the data table).
next, we have a text box for user to enter the column name.
And then a button get max, which will use the text box with column name.
After that, we have a text box to show the results.
So, we have this code:
Dim rstData As New DataTable
Private Sub cmdLoadData_Click(sender As Object, e As EventArgs) Handles cmdLoadData.Click
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"SELECT * FROM tblhotelsA ORDER BY HotelName"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
MsgBox("Data loaded", MsgBoxStyle.Information)
End Using
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If rstData.Rows.Count > 0 Then
' find max colum based on colum name in
Dim MyResult As Object
MyResult = rstData.Compute($"MAX({txtColumn.Text})", "")
Debug.Print(MyResult.ToString())
txtMax.Text = $"Max value for colum {txtColumn.Text} = {MyResult.ToString()}
-- colum data type = {MyResult.GetType.ToString()}"
End If
End Sub
and the results are now this:
Edit: User wants to build a sql query to get the max value
Ok, so the question is NOT that we have a data table (dt) in code, and we wish to pull/get/find the max value from that vb.net dt.
our question is that we want to query the database for a given column, and PUT THE RESULTS into that vb.net data table.
So, we want to QUERY SQL server to get the one result.
So, a very different goal.
This would be a "more common" question, and thus amounts to a plain jane SQL query.
this also of course will perform MUCH faster, since we don't pull nor have that vb.net "dt" or datatable, but we are to put the results of the sql query into that dt.
So, our form can look the same, but now our code for the "Get max" button would be this:
We do NOT require the first button to "load data" anymore.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
$"SELECT MAX(#P1) FROM tblhotelsA"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#P1", SqlDbType.NVarChar).Value = txtColumn.Text
rstData.Load(cmdSQL.ExecuteReader)
txtMax.Text = $"Max value for colum {txtColumn.Text} = {rstData.Rows(0)(0).ToString()}"
End Using
End Using
Now, say we want to "ask" the user for a given city, and then return the max found age for that user supplied city.
Then this:
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
$"SELECT MAX(Age) FROM tblhotelsA WHERE City = #City"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtWhatCity.Text
rstData.Load(cmdSQL.ExecuteReader)
txtMax.Text = $"Max age found for city = {txtcity.Text} = {rstData.Rows(0)(0).ToString()}"
End Using
End Using

Weekly Data show

Please any one help me, I just making a micro finance type software, there was a problem I want to show every week data from access database to vb.net datagrid view but don't work my code,
I insert EntryDate Savings Entry Lable Date (lblSavingsEntryDate.Text = Date.Now.ToString("dd/MM/yyyy"))
Here is my Code
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1).ToString("dd/MM/yyyy")
Dim todate = DateTime.Now.AddDays(0).ToString("dd/MM/yyyy")
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN '" + Sunday + "' And '" + todate + "'"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
Please Help... How can show data in every week.
It's much more secure and safer way using Parameters (DataAdapter will convert in proper way date, datetime format in sql) instead converting date into string, especially because different date formats and avoiding sql injection.
Bellow is example with using Parameters in, let say, source format (in this case date data type) :
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1)
Dim todate = DateTime.Now.AddDays(0)
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN #sunday AND #todate;"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
da.SelectCommand.Parameters.AddWithValue("#sunday", Sunday)
da.SelectCommand.Parameters.AddWithValue("#todate", todate)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
By this way You don't have to worry about date format conversion.
You trying to compare a date (string date) as "dd/MM/yyyy" format and you have a big problem because your query will be like this in runtime :
WHERE EntryDate BETWEEN '11/02/2018' And '12/02/2018'
Result : Tons of strings are between these dates
For example : '11/02/2018','11/03/2018','11/04/2018', even another year like '11/02/2019'
In string compare, early characters always compare first and they are more important in compare system (in this case your 4 chars for year have less priority than month and even day)
Solution :
Use this format for saving your date :
.ToString("yyyy/MM/dd")
So your code should be like this :
Private Sub btnBalanceWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBalanceWeekly.Click
Dim Sunday = DateTime.Now.AddDays((Today.DayOfWeek - DayOfWeek.Sunday) * -1).ToString("yyyy/MM/dd")
Dim todate = DateTime.Now.AddDays(0).ToString("yyyy/MM/dd")
Try
Dim sqlstr1 As String
sqlstr1 = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN '" + Sunday + "' And '" + todate + "'"
Dim da As New OleDbDataAdapter(sqlstr1, conn2)
Dim dt As New DataTable("Receivedtbl")
da.Fill(dt)
dgvBalanceSavings.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn2.Close()
Me.BalanceTotalSeavings()
Me.BalanceGrpReceived()
Me.BalanceCusReceived()
End Try
End Sub
But remember you need save your date string with this format too (old dates which already saved in your database)
First and forever turn on Option Strict. Compile Time errors - good, you can fix them. Runtime errors bad, you might not catch them.
Add two DateTimePicker controls to your form and appropriate labels. There are all kinds of properties you can set if the defaults don't suit you.
The following code shows you how to use parameters with your SQL strings. This not only saves you headaches formating your string but could save your database from malicious input.
Private Sub GetSavings()
Dim da As New OleDbDataAdapter
Dim strSQL As String = "SELECT * FROM Receivedtbl WHERE EntryDate BETWEEN #FromDate And #ToDate;"
Dim FromDate As Date = DateTimePicker1.Value.Date
Dim ToDate As Date = DateTimePicker2.Value.Date
If FromDate >= ToDate Then
MessageBox.Show("From date must be earlier than To date.")
Exit Sub
End If
Dim cmd As New OleDbCommand With {
.Connection = conn2,
.CommandType = CommandType.Text,
.CommandText = strSQL}
'Access cares not about the parameter names but about there order
cmd.Parameters.Add("#FromDate", OleDbType.Date).Value = FromDate
cmd.Parameters.Add("#ToDate", OleDbType.Date).Value = ToDate
da.SelectCommand = cmd
'now continue with your .Fill code
End Sub

How do I change data type to fix data type mismatch in criteria expression

I'm trying to get the database value of an item that i put on a listbox to display to the textbox. (vb.net)
My database table name is 'productlog', in this table has 3 columns, productid, productname, and price. I got the productname to display on a listbox that I made, now I am attempting to display the 3 columns on 3 textboxes. However, I get the "data type mismatch in criteria expression" error on my ExecuteReader line. Here's my code:
Public Class shop
Dim provider As String
Dim datafile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Dim lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Dim lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid =' & listboxitems.Text & ' AND product ='" & listboxitems.Text & "' AND price =' & listboxitems.Text & '", lbconn)
Dim lbreader As OleDbDataReader
lbconn.Open()
lbreader = lbcmd.ExecuteReader() 'error appearing right here'
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid")
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price")
End While
lbconn.Close()
End Sub
Based on the other questions that I looked up, it might be because that 'productid' and 'price' are both integers and what I'm doing is for a String. I tried to remove the double quotes ('"& txtproductid.Text"') and turn them into 'txtproductid.Text', based from another question I looked up. The another answer that I saw was to convert the string into an integer - 'lbcmd.Parameters.AddwithValue("#productid", ConvertInt32("txtproductid.Text"))' not sure if that's correct but I ended up getting the same error. How do I work around this error? Thanks.
UPDATED CODE:
Private Sub listboxitems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listboxitems.SelectedIndexChanged
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
Dim prodidparam As New OleDbParameter("#productid", Me.txtproductid.Text)
Dim prodparam As New OleDbParameter("#product", Me.txtproduct.Text)
Dim priceparam As New OleDbParameter("#price", Me.txtprice.Text)
lbcmd.Parameters.Add(prodidparam)
lbcmd.Parameters.Add(prodparam)
lbcmd.Parameters.Add(priceparam)
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
End Sub
You should not use string concatenation to create your SQL query as you are doing here. That opens you up to a sql injection hack. Instead you should use a parameterized query.
Try something like this (not tested):
Using lbconn As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.Oledb.12.0; Data Source = C:\Users\USER PC\Desktop\orderDB1.accdb")
Using lbcmd As New OleDb.OleDbCommand("SELECT productid, product, price FROM productlog WHERE productid = ? AND product = ? AND price = ?", lbconn)
'Set your values here. The parameters must be added in the same order that they
'appear in the sql SELECT command
lbcmd.Parameters.Add("productid", OleDb.OleDbType.Integer).Value = 1234
lbcmd.Parameters.Add("product", OleDb.OleDbType.VarChar).Value = "value of product"
lbcmd.Parameters.Add("price", OleDb.OleDbType.Integer).Value = 999
'Open the connection
lbconn.Open()
Using lbreader As OleDbDataReader = lbcmd.ExecuteReader()
While lbreader.Read
txtproductid.Text = lbreader.GetInt32("productid").ToString()
txtproduct.Text = lbreader.GetString("product")
txtprice.Text = lbreader.GetInt32("price").ToString()
End While
End Using
End Using
End Using
Since your code is using OleDbConnection you can't use named parameters. Note the question marks in the SELECT statement which server as placeholders for the values.
Note that when using OleDb, you have to add the parameters in the same order as they appear in your sql query.
The Using ... End Using statements ensure that the connection, command and datareader are disposed properly.

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

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

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