SELECT Query WHERE multiple values from checkboxlist are used - sql

I was wondering if it was possible to filter down data from a table using multiple values from a checkboxlist? (or any other way) I have a checkboxlist and a gridview and when you check on of the boxes it does show the right data in the gridview but the problem arises when I try to check multiple values. It seems to search for the first checked value and then ignores the rest. You'd think it'd be simple! Perhaps it is. Here is my attempt below.
CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim strSQL As New System.Text.StringBuilder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
FillGridView()
End If
End Sub
Private Sub FillGridView()
Dim strMyConn As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
Using MyConn As New SqlClient.SqlConnection(strMyConn)
MyConn.Open()
Dim cmd As New SqlClient.SqlCommand(strSQL.ToString, MyConn)
cmd.Connection = MyConn
cmd.CommandType = CommandType.Text
Try
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
If Me.GridView1.Visible = False Then Me.GridView1.Visible = True
Catch ex As Exception
Me.GridView1.Visible = False
End Try
End Using
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
If c <> 0 Then
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
End If
End Sub
End Class

Refactor this section to create a WHERE IN statement so it checks to see if the value is found among any item checked
Before
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
After
Dim params As StringBuilder = New StringBuilder()
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
params.Append("'")
params.Append(CheckBoxList1.Items(i).Text)
If i < Me.CheckBoxList1.Items.Count Then
params.Append("',") // don't append a comma if it's the last item
End If
End If
Next
strSQL.Append("SELECT Project.* FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID WHERE Keyword.Keyword in (")
strSQL.Append(params.ToString()) // append comma delimited values that make up where in statement
strSQL.Append("')") // close where in statement
FillGridView()

Related

Find and highlight the max value in from multiple column in VB.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error
maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

vb.net Task.Factory multiple tasks needed?

Is this asynchronous programming correct ?
Since this is my first time using TAP, I want to make sure I do it correctly from the beginning.
I want to fill a table from a ODBC database and afterwards read some files and extract values out of it, without freezing my UI.
Why do I need to run OdbcDataAdapter and the file reading as tasks if I run the whole Function as a task in my UI Sub ? Otherwise it blocks my UI. thread.
UI Code
Private Async Sub frmOfsList_Shown(sender As Object, e As EventArgs) Handles MyBase.Show
Dim sw As New Stopwatch 'query time
sw.Start()
DataGridView1.Visible = False
Label2.Visible = False
DataGridView1.DataSource = Await OFS.GetJobList 'async method
sw.Stop()
Label2.Text = "Query time: " & sw.Elapsed.TotalSeconds & "s"
For i As Integer = 0 To DataGridView1.Rows.Count - 1 'color days until prodution date
If DataGridView1.Rows(i).Cells(3).Value < 0 Then
DataGridView1.Rows(i).Cells(3).Style.ForeColor = Color.Red
Else
DataGridView1.Rows(i).Cells(3).Style.ForeColor = Color.Green
End If
Next
DataGridView1.Visible = True 'show grid
DataGridView1.ClearSelection()
Label2.Visible = True
End Sub
Async Function
Public Shared Async Function GetJobList() As Task(Of DataTable)
Dim dq As Char = """"
Dim con As OdbcConnection = New OdbcConnection(constr)
con.Open()
'get data from OFS
Dim cmd As String = "SELECT p1.ProductionOrder, p1.Project, p1.ProductionDate, p1.Item, p1.Revision, p1.PlannedQty FROM " &
dq & "OFS460" & dq & "." & dq & "dbo" & dq & "." & dq & "tblProductionOrders" & dq & " p INNER JOIN " & dq & "OFS460" & dq & "." & dq & "dbo" &
dq & "." & dq & "tblProductionOrders" & dq & " p1 ON p.ProductionOrder = p1.ProductionOrder WHERE (p.Task=2820 AND p.StatusID=4) AND (p1.Task=2830 AND (p1.StatusID=1 OR p1.StatusID=2 OR p1.StatusID=3)) ORDER BY p1.ProductionDate"
Dim adapter As OdbcDataAdapter = New OdbcDataAdapter(cmd, con)
Dim datatable As New DataTable("JobList")
'fil table with job data async
Await Task.Factory.StartNew(Sub()
adapter.Fill(datatable)
End Sub)
'add columns to table
datatable.Columns.Add("Length", GetType(Double))
datatable.Columns.Add("Outside Dia", GetType(Double))
Dim proddate As DateTime
datatable.Columns.Add("Days until").SetOrdinal(3)
'calculate days
For j As Integer = 0 To datatable.Rows.Count - 1
proddate = datatable(j)(2)
datatable.Rows(j)(3) = proddate.Subtract(DateTime.Now).Days
Next
'Get length and diameter for each part
Dim searchpath As String = My.Settings.g250path
Await Task.Factory.StartNew(Sub()
Dim files As String()
Dim filetext As String
For i As Integer = 0 To datatable.Rows.Count - 1
files = System.IO.Directory.GetFiles(searchpath, "*" & datatable.Rows(i)("Item") & "*") 'get file by item#
If files.Length > 0 Then
filetext = System.IO.File.ReadAllText(files(0)) 'read file
datatable.Rows(i)("Length") = ProgramManager.GetValue(filetext, "I_R872", 7).ToString 'extract values
datatable.Rows(i)("Outside Dia") = ProgramManager.GetValue(filetext, "I_R877", 7).ToString
End If
Next i
End Sub)
Return datatable
End Function
You should not use Task.Factory.StartNew with Async-Await. You should use Task.Run, instead.
And you only need to get out of the UI thread once for the "heavy work" and return when done.
Try this:
Public Shared Function GetJobList() As DataTable
Dim dq As Char = """"
Dim con As OdbcConnection = New OdbcConnection(constr)
con.Open()
'get data from OFS
Dim cmd As String = "SELECT p1.ProductionOrder, p1.Project, p1.ProductionDate, p1.Item, p1.Revision, p1.PlannedQty FROM ""OFS460"".""dbo"".""tblProductionOrders"" p INNER JOIN ""OFS460"".""dbo"".""tblProductionOrders"" p1 ON p.ProductionOrder = p1.ProductionOrder WHERE (p.Task=2820 AND p.StatusID=4) AND (p1.Task=2830 AND (p1.StatusID=1 OR p1.StatusID=2 OR p1.StatusID=3)) ORDER BY p1.ProductionDate"
Dim adapter As OdbcDataAdapter = New OdbcDataAdapter(cmd, con)
Dim datatable As New DataTable("JobList")
'fil table with job data async
adapter.Fill(datatable)
'add columns to table
datatable.Columns.Add("Length", GetType(Double))
datatable.Columns.Add("Outside Dia", GetType(Double))
Dim proddate As DateTime
datatable.Columns.Add("Days until").SetOrdinal(3)
'calculate days
For j As Integer = 0 To datatable.Rows.Count - 1
proddate = datatable(j)(2)
datatable.Rows(j)(3) = proddate.Subtract(DateTime.Now).Days
Next
'Get length and diameter for each part
Dim searchpath As String = My.Settings.g250path
Dim files As String()
Dim filetext As String
For i As Integer = 0 To datatable.Rows.Count - 1
files = System.IO.Directory.GetFiles(searchpath, "*" & datatable.Rows(i)("Item") & "*") 'get file by item#
If files.Length > 0 Then
filetext = System.IO.File.ReadAllText(files(0)) 'read file
datatable.Rows(i)("Length") = ProgramManager.GetValue(filetext, "I_R872", 7).ToString 'extract values
datatable.Rows(i)("Outside Dia") = ProgramManager.GetValue(filetext, "I_R877", 7).ToString
End If
Next i
Return datatable
End Function
And invoke it like this:
DataGridView1.DataSource = Await Task.Run(AddressOf OFS.GetJobList1)
This way, the OFS.GetJobList1 function will be scheduled to execute on a thread pool thread and, when completed, the execution will resume on the caller sub/function and the return value of Task.Run (which is the return value of OFS.GetJobList1 wrapped with a Task(Of DataTable)) will be unwrapped and assigned to DataGridView1.DataSource.

Winforms Textbox Autocomplete Crash Application

Sometimes the program crashes when I write in the textbox. I can't find the solution. It is very weird situation. Why is program crashes sometimes. Here codes:
Private Sub CreateProductNameAutoCompleteSource(ByVal tamamlamaturu As Byte)
Dim sql_ProductName As String
Dim gorkemDAL As New Aktuel.Data.SqlClient(cns_ScalaConnectionString)
Dim dtbl_ProductName As DataTable
Dim X As New AutoCompleteStringCollection
Dim parcakodu
If tamamlamaturu = tamamlamatipi.talepedilenparca Then parcakodu = txt_talepedilenparca.Text
If tamamlamaturu = tamamlamatipi.gonderilenparca Then parcakodu = txt_gonderilenparca.Text
sql_ProductName = "select distinct urunkodu from urunler where urunkodu like '" & parcakodu & "%' order by urunkodu asc"
gorkemDAL.OpenDbConnection()
dtbl_ProductName = gorkemDAL.ExecuteTable(sql_ProductName)
gorkemDAL.CloseDbConnection()
For Each row As DataRow In dtbl_ProductName.Rows
X.Add(row(0).ToString)
Next
If tamamlamaturu = tamamlamatipi.talepedilenparca Then
txt_talepedilenparca.AutoCompleteSource = AutoCompleteSource.CustomSource
txt_talepedilenparca.AutoCompleteCustomSource = X
txt_talepedilenparca.AutoCompleteMode = AutoCompleteMode.Suggest
End If
If tamamlamaturu = tamamlamatipi.gonderilenparca Then
txt_gonderilenparca.AutoCompleteSource = AutoCompleteSource.CustomSource
txt_gonderilenparca.AutoCompleteCustomSource = X
txt_gonderilenparca.AutoCompleteMode = AutoCompleteMode.Suggest
End If
End Sub
And Textchange event :
Private Sub txt_talepedilenparca_TextChanged(sender As Object, e As EventArgs) Handles txt_talepedilenparca.TextChanged
CreateProductNameAutoCompleteSource(tamamlamatipi.talepedilenparca)
End Sub
And I found error message in event viewer:
Error Message
Error Message
The code looks pretty clean, I can't see anything too obvious but I would make sure that parcakodu doesn't contain any sql terminating speech marks:
i.e.
sql_ProductName = "select distinct urunkodu from urunler where urunkodu like '" & parcakodu & "%' order by urunkodu asc"
becomes:
sql_ProductName = "select distinct urunkodu from urunler where urunkodu like '" & parcakodu.Replace("'", "''") & "%' order by urunkodu asc"
(you may want to copy & paste as hard to see what I've done there)
I would also wrap your ForEach statement in a null check - could it be you're trying to access dtbl_ProductName when it's null? Accessing the property .Rows will raise an exception if the object is null itself is Nothing.
Try something like:
If (dtbl_ProductName IsNot Nothing)
For Each row As DataRow In dtbl_ProductName.Rows
X.Add(row(0).ToString)
Next
End If
Failing that - check if you can make it crash every time by using a known search string that has caused it to crash in the past. Is there a character in the string sql doesn't like, or is the result set of your sql query empty?
In your reply to the question about the error you're receiving you said the program is just closing.
Thus, the first step is to wrap your code in a Try...Catch block in order to get a meaningful error message without getting the program to close.
Private Sub CreateProductNameAutoCompleteSource(ByVal tamamlamaturu As Byte)
Try
Dim sql_ProductName As String
Dim gorkemDAL As New Aktuel.Data.SqlClient(cns_ScalaConnectionString)
Dim dtbl_ProductName As DataTable
Dim X As New AutoCompleteStringCollection
Dim parcakodu
If tamamlamaturu = tamamlamatipi.talepedilenparca Then
parcakodu = txt_talepedilenparca.Text
ElseIf tamamlamaturu = tamamlamatipi.gonderilenparca Then
parcakodu = txt_gonderilenparca.Text
Else
Exit Sub
End If
sql_ProductName = "select distinct urunkodu from urunler where urunkodu like '" & parcakodu.Replace("'", "''") & "%' order by urunkodu asc"
gorkemDAL.OpenDbConnection()
dtbl_ProductName = gorkemDAL.ExecuteTable(sql_ProductName)
gorkemDAL.CloseDbConnection()
If (dtbl_ProductName IsNot Nothing) Then
For Each row As DataRow In dtbl_ProductName.Rows
X.Add(row(0).ToString)
Next
End If
If tamamlamaturu = tamamlamatipi.talepedilenparca Then
txt_talepedilenparca.AutoCompleteSource = AutoCompleteSource.CustomSource
txt_talepedilenparca.AutoCompleteCustomSource = X
txt_talepedilenparca.AutoCompleteMode = AutoCompleteMode.Suggest
End If
If tamamlamaturu = tamamlamatipi.gonderilenparca Then
txt_gonderilenparca.AutoCompleteSource = AutoCompleteSource.CustomSource
txt_gonderilenparca.AutoCompleteCustomSource = X
txt_gonderilenparca.AutoCompleteMode = AutoCompleteMode.Suggest
End If
Catch ex As Exception
MessageBox.Show(String.Format("The following error has occured:{0}{1}", vbCrLf, ex.Message), "An error has occured")
End Try
End Sub
Private Sub txt_talepedilenparca_TextChanged(sender As Object, e As EventArgs) Handles txt_talepedilenparca.TextChanged
If txt_talepedilenparca.Text.Length >= 3 Then
CreateProductNameAutoCompleteSource(tamamlamatipi.talepedilenparca)
End If
End Sub
This will give a clear idea about what's happening before tackling the main issue.
I've also escaped the string value being passed to the query so it doesn't create an SQL injection if the user entered a single quote in the text boxes.
I've also limited the function not trigger but until the textbox has at least 3 letters.
If the program still closes without an error message, then the issue is happening elsewhere, but if you got an error message, then we can take it from there.
Try to use this trick:
Private Sub txt_talepedilenparca_TextChanged(sender As Object, e As EventArgs) Handles txt_talepedilenparca.TextChanged
Dim sql_ProductName As String
Dim gorkemDAL As New Aktuel.Data.SqlClient(cns_ScalaConnectionString)
Dim dtbl_ProductName As DataTable
Dim X As New AutoCompleteStringCollection
sql_ProductName = "select distinct urunkodu from urunler where urunkodu order by urunkodu asc"
gorkemDAL.OpenDbConnection()
dtbl_ProductName = gorkemDAL.ExecuteTable(sql_ProductName)
gorkemDAL.CloseDbConnection()
try
If txt_talepedilenparca.lenght >= 3 and txt_talepedilenparca.lenght mod 3 = 0 then
For Each row As DataRow In dtbl_ProductName.select("urunkodu like '*" & parcakodu & "*'")
X.Add(row(0).ToString)
Next
if x.count > 0
txt_talepedilenparca.AutoCompleteSource = AutoCompleteSource.CustomSource
txt_talepedilenparca.AutoCompleteCustomSource = X
txt_talepedilenparca.AutoCompleteMode = AutoCompleteMode.Suggest
end if
End If
catch ex as exception
msgbox(ex.tostring)
end try
End Sub

VB How to Clear existing items in listview

I am trying to search the information from the sql server then show at the listview. Everytime I click search it won't clear the existing records based on the past time searching. I've tried item.clear, it will only show me the new search but it won't clear all the existing records. Can someone help please?
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim strNameSource As String
Dim strPhoneSource As String
Dim strBothSource As String
If OpenConnect() = True Then
Try
If ChkCustName.Checked = True Then
strNameSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strNameSource)
ElseIf ChkPhoneNumber.Checked = True Then
strPhoneSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "'"
SearchReservation(strPhoneSource)
ElseIf ChkCustName.Checked = True And ChkPhoneNumber.Checked = True Then
strBothSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "' AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strBothSource)
End If
txtLastName.Clear()
txtPhoneNumber.Clear()
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End If
End Sub
Private Sub SearchReservation(ByVal strSource As String)
Dim itemcollection(100) As String
Dim Row As Integer
Dim Column As Integer
Dim ListViewItem As New ListViewItem
lstReservation.Items.Clear()
Try
cmd = New OleDb.OleDbCommand(strSource, cnn)
Adapter = New OleDb.OleDbDataAdapter(cmd)
Adapter.Fill(Ds, "Table")
'Now adding the Items in Listview
If Ds.Tables(0).Rows.Count = 0 Then
' Something went wrong. warn user
MessageBox.Show(Me, "Could not find the Customer", "Customer finding Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstReservation.BeginUpdate()
For Row = 0 To Ds.Tables(0).Rows.Count - 1
For Column = 0 To Ds.Tables(0).Columns.Count - 1
itemcollection(Column) = Ds.Tables(0).Rows(Row)(Column).ToString()
Next
ListViewItem = New ListViewItem(itemcollection)
lstReservation.Items.Add(ListViewItem)
Next
lstReservation.EndUpdate()
End If
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End Sub
Lots of issues with your code, but I'll focus on your immediate issue.
You keep filling the DataSet with new tables, but you keep using the original table that is still in position zero of the DataSet.
I would venture a guess that you need to clear the rows of your DataTable:
If Ds.Tables.Contains("Table") Then
Ds.Tables("Table").Rows.Clear()
End If
lstReservation.Items.Clear()
of just clear any tables there:
Ds.Tables.Clear()
lstReservation.Items.Clear()

multiple SQL queries stored as vb.net variable

I know there are a few other posts about putting sql results into a vb.net variable but I just couldn't wrap my head around how they did it and how I could do it in my project.
So what I'm trying to do is query my database for 4 different values and then display each value in a certain part of the form. I was going to store the each value into a variable and then do an textbox1.text = i
Updated code for 10/5/2014
Private Sub LBmembers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
Dim i As String = LBmembers.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime, WorkPercent, Share FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = i
Using reader = cmd.ExecuteReader()
If reader.Read() Then
TBtimestart.Text = reader.ToString(0)
TBtimeend.Text = reader.ToString(1)
Dim j = Convert.ToInt32(reader.ToString(2))
TBtimecycle.Text = reader.GetInt32(3).ToString
TBmemberpercent.Text = reader.GetInt32(4)
TBmembershare.Text = reader.GetInt32(5)
If j = 1 Then
RBpro.Checked = True
ElseIf j = 2 Then
RBret.Checked = True
ElseIf j = 3 Then
RBcov.Checked = True
ElseIf j = 4 Then
RBskiff.Checked = True
ElseIf j = 5 Then
RBmack.Checked = True
ElseIf j = 6 Then
RBhulk.Checked = True
Else
RBpro.Checked = False
RBret.Checked = False
RBcov.Checked = False
RBskiff.Checked = False
RBmack.Checked = False
RBhulk.Checked = False
Exit Sub
End If
End If
End Using
con.Close()
End Using
End Using
End Sub
The exception
InvalidCastException was unhandled Specified cast is not valid.
Pops up on the line TBtimecycle.text = reader.GetInt32(3).ToString
The reader is also reading "System.Data.OleDb.OleDbDataReader" when I insert the test code "TBgrossisk.Text = reader.ToString()" into the using statement
If you look carefully to the syntax of the SELECT statement you will see that you can request any column of the table with just one query.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LBmembers.SelectedIndexChanged
if string.IsNullOrWitheSpace(ListBox1.SelectedItem.ToString()) Then
MessageBox.Show("Select an item from the Listbox")
End If
Dim member As String = ListBox1.SelectedItem
Dim dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource = "Data Source= C:\members.mdb "
Dim SqlQuery As String = "SELECT StartTime, EndTime, ShipCode, CycleTime " & _
"FROM tblMembers WHERE Member = #ID;"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(SqlQuery, con)
con.Open()
cmd.Parameters.AddWithValue("#ID", OleDb.OleDbType.VarWChar).Value = member
Using reader = cmd.ExecuteReader
if reader.Read() Then
TextBox1.Text = reader.GetString(0)
TextBox2.Text = reader.GetString(1)
Dim j = reader.GetInt32(2)
If j = 1 Then
Radio1.Checked = True
ElseIf j = 2 Then
Radio2.Checked = True
ElseIf j = 3 Then
Radio3.Checked = True
ElseIf j = 4 Then
Radio4.Checked = True
ElseIf j = 5 Then
Radio5.Checked = True
ElseIf j = 6 Then
Radio6.Checked = True
Else
Exit Sub
End If
TextBox4.Text = reader.GetInt32(3).ToString()
Else
MessageBox.Show("The search for '" & member & "' doesn't find any data")
End If
End Using
End Using
End Using
End Sub
Instead of using ExecuteScalar that returns just the first column of the first row retrieved you could use an OleDbDataReader returned by the method ExecuteReader. This object allows to access the various column in the current record using an index (or the column name). Read more about OleDbDataReader in MSDN