multiple SQL queries stored as vb.net variable - sql

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

Related

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

Oracle database errors with vb.net

I am tasked with making a simple GUI based database viewer. The database is hosted on our schools ftp server we must use visual basic and for the most part I've got it working I can search, view, and add to the database, but editing an existing record is giving me problems.
When I attempt to update the record I get a ora-00904 error invalid identifier when not using a colon (:) in where portion of the query and an ora-01008 not variables bound with a colon (:). We so far have only really used sqldeveloper and as a final project we were asked to use Visual Basic but we never covered anything like this in class so its a challenge I suppose.
PS: I only have that portion commented out so that I could view the error.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim strCustomerEmail As String = ""
Dim strLastName As String = ""
Dim strFirstName As String = ""
Dim strAddress As String = ""
Dim strCity As String = ""
Dim strState As String = ""
Dim intZip As Integer = 0
Dim datDateSignedUp As Date
Dim intCustomerNumber As Integer = 0
Try
strCustomerEmail = CStr(txtCustomerEmail.Text)
strLastName = CStr(txtLastName.Text)
strFirstName = CStr(txtFirstName.Text)
strAddress = CStr(txtAddress.Text)
strCity = CStr(txtCity.Text)
strState = CStr(txtState.Text)
intZip = CInt(txtZip.Text)
datDateSignedUp = CDate(txtDateSignedUp.Text)
intCustomerNumber = CInt(txtCustomerNumber.Text)
Dim sql As String = "UPDATE P_CLIENTS SET CUSTOMER_EMAIL = :CUSTOMER_EMAIL, LASTNAME = :LASTNAME, FIRSTNAME = :FIRSTNAME, ADDRESS = :ADDRESS, CITY = :CITY, STATE = :STATE, ZIP = :ZIP, DATE_SIGNED_UP = :DATE_SIGNED_UP, CUSTOMER# = :CUSTOMER# WHERE CUSTOMER_EMAIL = :EDIT_CUSTOMER_EMAIL"
Dim cmd2 As New OracleCommand(sql, conn)
conn.Open()
cmd2.Parameters.Add("CUSTOMER_EMAIL", strCustomerEmail)
cmd2.Parameters.Add("LASTNAME", strLastName)
cmd2.Parameters.Add("FIRSTNAME", strFirstName)
cmd2.Parameters.Add("ADDRESS", strAddress)
cmd2.Parameters.Add("CITY", strCity)
cmd2.Parameters.Add("STATE", strState)
cmd2.Parameters.Add("ZIP", intZip)
cmd2.Parameters.Add("DATE_SIGNED_UP", datDateSignedUp)
cmd2.Parameters.Add("EDIT_CUSTOMER_EMAIL", strEditCustomerEmail)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
txtCustomerEmail.Text = strEditCustomerEmail
txtLastName.Text = ""
txtFirstName.Text = ""
txtAddress.Text = ""
txtCity.Text = ""
txtState.Text = ""
txtZip.Clear()
txtDateSignedUp.Clear()
txtCustomerNumber.Clear()
'txtCustomerEmail.Select()
txtCustomerEmail.Enabled = True
txtLastName.Enabled = True
txtFirstName.Enabled = True
txtAddress.Enabled = True
txtCity.Enabled = True
txtState.Enabled = True
txtZip.Enabled = True
txtDateSignedUp.Enabled = True
txtCustomerNumber.Enabled = True
'Catch ex As Exception
' MessageBox.Show("An error occurred while attempting to add a new record.", "Error")
Finally
conn.Close()
txtCustomerEmail.Select()
End Try
End Sub
You are missing Customer# from your parameter list.

No data exists for the row/column vb.net

Path variable is defined globally.
Values of er.item(0),er.item(1), er.item(2),er.item(2),er.item(3) are not accessible after reader object has used item(0). What is wrong?
here is the code
Private Sub load_qc_by()
Dim dname = CategoryDropDown2.Text
con.ConnectionString = path
cmd.Connection = con
con.Open()
cmd.CommandText = "SELECT SQC_By,PQC_By,FQC_By,CQC_By FROM Deliverables WHERE Deliverable ='" & dname & "' AND Project='" & ProjectDropDown2.Text & "'"
Dim er As OleDbDataReader = cmd.ExecuteReader
If er.HasRows Then
While er.Read
If (er.Item(0).ToString.Equals("NA")) Then
Call load_all_Names("sqcby_combobox")
sqcby_combobox.SelectedIndex = 0
Else
MessageBox.Show(er.Item(0))
sqcby_combobox.Text = er.Item(0).ToString
sqcby_combobox.Enabled = False
End If
If (er.Item(1).ToString.Equals("NA")) Then
Call load_all_Names("pqcby_combobox")
pqcby_combobox.SelectedIndex = 0
Else
MessageBox.Show(er.Item(1))
pqcby_combobox.Text = er.Item(1)
pqcby_combobox.Enabled = False
End If
If (er.Item(2).ToString.Equals("NA")) Then
Call load_all_Names("fqcby_combobox")
fqcby_combobox.SelectedIndex = 0
Else
MessageBox.Show(er.Item(2))
fqcby_combobox.Text = er.Item(2)
fqcby_combobox.Enabled = False
End If
If (er.Item(3).ToString.Equals("NA")) Then
Call load_all_Names("cqcby_combobox")
cqcby_combobox.SelectedIndex = 0
Else
MessageBox.Show(er.Item(3))
cqcby_combobox.Text = er.Item(3)
cqcby_combobox.Enabled = False
End If
End While
End If
er.Close()
con.Close()
End Sub

SELECT Query WHERE multiple values from checkboxlist are used

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

loop data in datalist

How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
Protected Sub DataList2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList2.ItemDataBound
For Each li As DataListItem In DataList2.Items
Dim labelasd As Label = DirectCast(e.Item.FindControl("**Label8**"), Label)
Dim reviewid As Integer = labelasd.Text
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select Count(reviewYes) AS Expr1 From ProductReviewHelp Where ProductReviewID = " & reviewid & ""
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim countofreview As Integer = 0
Dim reviewcountboolean As Boolean
If (reader.Read()) Then
If (IsDBNull(reader.GetValue(0)) = False) Then
countofreview = reader.GetValue(0)
End If
End If
If countofreview = 0 Then
reviewcountboolean = False
Else
reviewcountboolean = True
End If
If (reviewcountboolean = True) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "Hello"
ElseIf (reviewcountboolean = False) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "No"
End If
Next
End Sub
How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
You are looping on your DataList2 items but, at every loop, you update the label7 with the logic of the current item, effectively removing the result of the previous loop. This means that, when you reach the last item, the Label7 will reflect the string "Hello" or "No" depending on the logic applied to the last item in your loop.
Apart from this logical error, you have also numerous errors in the code shown.
The connection is never closed.
You use string concatenation instead of parameters.
You use ExecuteReader when in this case an ExecuteScalar is better
suited.
You can iterate through then using a loop here is an example
Try
readFromDL1 = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
readFromQ = DirectCast(SqlDataSource7.Select(DataSourceSelectArguments.Empty), DataView)
Catch ex As Exception
End Try
'End
'datalist1
i = 0
_rowCount = DataList1.Items.Count
If _rowCount > 0 Then
_getCall = DataList1.Items.Item(i).FindControl("lnkEdit")
End If
For Each readr As DataRowView In readFromQ
findQNumber = readr(1).ToString()
For Each readfdlr1 As DataRowView In readFromDL1
findQNumber1 = readfdlr1(1).ToString
Try
indexofitems = DataList1.Items.Item(i1).ItemIndex
If findQNumber.ToString = findQNumber1.ToString Then
_getCall = DataList1.Items.Item(indexofitems).FindControl("lnkEdit")
_getCall.Text = "Called"
_getCall.Enabled = False
_getCall.ForeColor = Drawing.Color.Red
_getCall.BackColor = Drawing.Color.Yellow
End If
i1 = i1 + 1
Catch e As Exception
End Try
Next
i1 = 0
i = i + 1