Search function using listview in vb - database

i get a change of data in a first column in a listview after search a data.
Example:
in a first column, the data must display a room code like "3234" but after do a searching the data change to "Room_Code".
Below is the code for search function
Private Sub Search()
ListViewRoom.Items.Clear()
Dim item As New ListViewItem
Dim _isFound As Boolean = False
Dim colName() As String = {"Room_Code", "Room_Type", "Room_No", "Room_Price", "Room_Status", "No_of_Occupancy"}
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy " & _
"FROM Room " & _
"WHERE " & colName(cboSearch.SelectedIndex) & " LIKE '%" & txtSearch.Text & "%'"
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Using con As New SqlClient.SqlConnection("Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True")
Using com As New SqlClient.SqlCommand()
With com
.Connection = con
.CommandType = CommandType.Text
.CommandText = strSqlSearch
End With
Try
con.Open()
Dim dr As SqlClient.SqlDataReader = com.ExecuteReader
While dr.Read
_isFound = True
item = ListViewRoom.Items.Add("Room_Code".ToString)
item.SubItems.Add(dr("Room_Type".ToString))
item.SubItems.Add(dr("Room_No".ToString))
item.SubItems.Add(dr("Room_Price".ToString))
item.SubItems.Add(dr("Room_Status".ToString))
item.SubItems.Add(dr("No_of_Occupancy".ToString))
End While
If Not _isFound Then
MsgBox("No results found.", MsgBoxStyle.OkOnly, "Information")
End If
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Using
End Using
Tq

Um, because you're telling it to:
item = ListViewRoom.Items.Add("Room_Code".ToString)
I suppose that that should be:
item = ListViewRoom.Items.Add(dr("Room_Code").ToString)
By the way, you've got several other pointless calls to ToString too, e.g.
item.SubItems.Add(dr("Room_Type".ToString))
What's the point of calling ToString on a literal? Surely it's the field value that you want converted to a String:
item.SubItems.Add(dr("Room_Type").ToString())
You really should be using a DataGridView and simply binding a DataTable instead of abusing a ListView, which is NOT a grid control.

Related

How to resolve : 'There is already an open DataReader associated with this Command which must be closed first.'

I've been trying to insert data into my sql database but this problem always show up
i've tried redoing it again and the same problem occurs and i'm really stumped right now
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim conn As SqlConnection = New SqlConnection("Data Source=DESKTOP-OBQR58O\SQLEXPRESS;Initial Catalog=Accounts;Integrated Security=True")
Dim comm As SqlCommand = New SqlCommand("insert into User(username, password)values('" + TextBox1.Text + "', '" + TextBox3.Text + "')", conn)
Dim data As SqlDataAdapter = New SqlDataAdapter(comm)
Dim user = TextBox1.Text
Dim pass = TextBox2.Text
Dim cpass = TextBox3.Text
Dim reader As SqlDataReader
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("select Username from [User] where Username ='" + TextBox1.Text + "'", conn)
conn.Close()
conn.Open()
reader = cmd.ExecuteReader
If user.Trim() = "" Or pass.Trim() = "" Or cpass.Trim() = "" Then
MessageBox.Show("Empty Fields", "Blank Spaces")
ElseIf Not String.Equals(pass, cpass) Then
MessageBox.Show("Passwords do not match", "ERROR")
conn.Close()
ElseIf reader.HasRows Then
MessageBox.Show("Username already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextBox1.Clear()
conn.Close()
reader.Close()
Else
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim log As New Login
Me.Close()
log.Show()
conn.Close()
End If
conn.Close()
End Sub
I honestly don't know what to do
You open your reader up at the top:
reader = cmd.ExecuteReader
So, it's open. And then, when you run the Fill command, it conflicts with the open reader!
The simplest fix - although, personally, I would restructure the code a bit, to bring the OpenReader nearer to where it is used - would be to add a Close to your reader right before the Fill.
Else
reader.Close() ' what you would add
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
VERY IMPORTANT: If you're not familiar with the concept of "SQL Injection Attacks", read up on them, right away. You should NEVER execute SQL that's been built by constructing a string with unvalidated data from the user. You should pass parameters instead.
After all, what if I typed in the user name of "Irrelevant';DROP TABLE Users;--"? You'd wind up with a SQL Statement that contained "SELECT Username from [Users] WHERE [Username] = 'Irrelevant'; DROP TABLE Users; --'"
And, of course, you should validate the input as well, for things like embedded HTML and script! But that's more complicated than just using SQL Parameters.

Database only adds (x) amount of rows before error system resources exceeded

I am having a problem with my code where i am only able to add so many lines of text before i get an error "system resources exceeded".
This is my code:
Dim x As Integer = MsgBox("Update Record?", MsgBoxStyle.YesNo, "Are you sure?")
If x = MsgBoxResult.Yes Then
Dim accessconn As New _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "MyDB.accdb")
Dim com As System.Data.OleDb.OleDbCommand
accessconn.Close()
Try
For Each strLine As String In TextBox1.Text.Split(vbNewLine)
accessconn.Open()
Dim str As String
Dim dr As OleDbDataReader
str = "SELECT * FROM Table4 WHERE MD5='" & strLine & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, accessconn)
dr = cmd.ExecuteReader
If dr.Read() Then
Label2.Text = Label2.Text + 1
Else
accessconn.Open()
com = New System.Data.OleDb.OleDbCommand("INSERT INTO Table4(MD5) VALUES('" & strLine & "')", accessconn)
com.ExecuteReader(CommandBehavior.CloseConnection)
Label3.Text = Label3.Text + 1
com.Dispose()
accessconn.Close()
End If
Next
accessconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
MsgBox("Done")
PopulateGridview4()
End If
I would like to be able to add unlimited rows of text to the database if possible. Please Help.
You should change your code to something like the following. Note that
Everything that returns an object like OleDbConnection, OleDbCommand, or OleDbDataReader is wrapped in a Using block. These objects all implement the IDisposable interface, which means they should be cleaned up as soon as you're done with them.
Also note that your INSERT did not return any data, so you should use ExecuteNonQuery instead of ExecuteReader.
Finally, please don't get into the habit of putting Try/Catch/End Try blocks around everything. You were displaying the exception (you displayed ex.ToString, which is a good thing), but you then ignored the exception. As a good general rule, don't catch exceptions unless you can fix them.
Code:
Dim x As Integer = MsgBox("Update Record?", MsgBoxStyle.YesNo, "Are you sure?")
If x = MsgBoxResult.Yes Then
Using accessconn As New _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "MyDB.accdb")
accessconn.Open()
For Each strLine As String In TextBox1.Text.Split(vbNewLine)
Dim str As String = "SELECT * FROM Table4 WHERE MD5='" & strLine & "'"
Using cmd As OleDbCommand = New OleDbCommand(str, accessconn)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.Read() Then
Label2.Text = Label2.Text + 1
Else
Using com As OleDbCommand = New System.Data.OleDb.OleDbCommand("INSERT INTO Table4(MD5) VALUES('" & strLine & "')", accessconn)
com.ExecuteNonQuery()
End Using
Label3.Text = Label3.Text + 1
End If
End Using
End Using
Next
MsgBox("Done")
PopulateGridview4()
End Using
End If
P.S. you could probably have made this a little less indented by using If x <> MsgBoxResult.Yes Then get out, but I don't know if this is inside of a Sub or Function, so "get out" could be different.

Search function using combo box,text box and list view

i have a few error. i have a search function from the database. when i run the project, and click the SEARCH button to view in the listview, the popup message out called "Incorrect syntax near "CONCAT". here the code for CONCAT
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
here full code for SEARCH function
Private Sub Search()
ListViewRoom.Items.Clear()
Dim item As New ListViewItem
Dim _isFound As Boolean = False
Dim colName() As String = {"Room_Code", "Room_Type", "Room_No", "Room_Price", "Room_Status", "No_of_Occupancy"}
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE CONCAT ('%', #valueName, '%')"
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Using con As New SqlClient.SqlConnection("Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True")
Using com As New SqlClient.SqlCommand()
With com
.Connection = con
.CommandType = CommandType.Text
.CommandText = strSqlSearch
.Parameters.AddWithValue("#valueName", txtSearch.Text)
End With
Try
con.Open()
Dim dr As SqlClient.SqlDataReader = com.ExecuteReader
While dr.Read
_isFound = True
item = ListViewRoom.Items.Add(dr("Room_Code").ToString)
item.SubItems.Add(dr("Room_Type".ToString))
item.SubItems.Add(dr("Room_No".ToString))
item.SubItems.Add(dr("Room_Price".ToString))
item.SubItems.Add(dr("Room_Status".ToString))
item.SubItems.Add(dr("No_of_Occupancy".ToString))
End While
If Not _isFound Then
MsgBox("No results found.", MsgBoxStyle.OkOnly, "Information")
End If
Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Using
End Using
End Sub
I hope u can help me. Tq
You don't need to use the CONCAT. just remove it from the SQL and it should work.
EDIT
Try this:
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%'+ #valueName +'%'"
Edit #2
Dim strSqlSearch As String = "SELECT Room_Code, Room_Type, Room_No, Room_Price, Room_Status, No_of_Occupancy" & _
"FROM Room" & _
"WHERE" & colName(cboSearch.SelectedIndex) & "LIKE '%" & txtSearch.Text & "%'"
And remove the parameter form the SqlCommand.

vb.net Datarepeater, Dataadapter, Dataset, SQL How to break up line by line and insert into repeater

Edited Code : the code from before works great but cannot change the textbox.text properties or display them fro each of the controlls added by this loop
any help is appreciated
some sub
Dim EqLst As String = ""
Try
Dim con As New SqlConnection
Dim myConString As String = getSQLString()
Dim objcommand As SqlCommand = New SqlCommand
With objcommand
.Connection = con
Dim cmdText As String = "SELECT EquipList from SiteAuditor where client='" & GLClient & "' and market='" & GLMarket & "' and project='" & GLProject & "'"
.CommandText = cmdText
End With
con.ConnectionString = myConString
con.Open()
Using readerObj As SqlClient.SqlDataReader = objcommand.ExecuteReader
'This will loop through all returned records
While readerObj.Read
EqLst = readerObj("EquipList").ToString
Exit While
End While
End Using
con.Close()
Dim li As String() = EqLst.Split(",")
Dim data As New List(Of dataitem)
For Each name As String In li
'Form1.DataRepeater1.AddNew()
data.Add(New dataitem(name))
Form1.DataRepeater1.CurrentItem.Controls("txtName").Text = name
Next
Form1.DataRepeater1.DataSource = data
I guess here is where i need be find out how to add / change my textox names within the datarpeater control anyone have any solutions for me ?
'For Each name As String In li
' Form1.DataRepeater1.CurrentItemIndex(i).text = name
'Next
Catch ex As Exception
Dim thiserror As String = "Error grabDataRepeaterData, " & vbCrLf _
& "Email Notifying CLS-Software Developemnt about this error was sent."
Dim additionalinfo As String = UserLogin & vbCrLf & UserLogin.Replace("CLSGROUP\", "") & vbCrLf & vbCrLf & vbCrLf & vbCrLf & vbCrLf & ex.ToString
MessageBox.Show(thiserror)
ErrorEmails(thiserror, additionalinfo)
End Try
Return Nothing
end sub
Public Class dataitem
Public Sub New(text As String)
Me.text = text
End Sub
Public Property text As String
End Class
The DataRepeater has to have its DataSource property set for AddNew to work. It's designed to be data bound.
You can set the dataSource to a list of objects. Then whenever you add to the list, the dataRepeater will automatically show the new items.
Example:
Public Class dataitem
Public Sub New(text As String)
Me.text = text
End Sub
Public Property text As String
End Class
Public Class Form1
Public Sub New()
InitializeComponent()
Dim data As New List(Of dataitem)
data.Add(New dataitem("test1"))
data.Add(New dataitem("test2"))
DataRepeater1.DataSource = data
End Sub
End Class
Your not declaring the datatype in your for each loop. You need 'as string' after 'name'
For Each name As String In li
Form1.DataRepeater1.AddNew()
Form1.DataRepeater1.CurrentItem.Controls("txtName").Text = name
Next

How to return database fields from checkbox selection?

the code below returns the fields of a given table ("Employee"), but I need to return the fields of ALL the tables in the given database, is this possible? My assumption is a For loop which loops round the tables in the database and prints the corresponding fields but my efforts seem to be in vain
Public Sub getDbFields()
Dim i As Integer
Dim dbcon As New System.Data.OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = " & dblocation & _
"\" & dbname)
Try
dbcon.Open()
dbDt = dbcon.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Columns, New Object() _
{Nothing, Nothing, "Employee", Nothing})
For i = 0 To dbDt.Rows.Count - 1
'compile lbtables with a list of available tables from the database
newLine()
frmMain.lstTables.Items.Add(dbDt.Rows(i)!COLUMN_NAME.ToString())
Next
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Load Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End Try
End Sub
This routine will be fired from the selection of a checkbox
This will return all columns on a database
Using con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + dblocation + "\" + dbname)
con.Open()
Dim schema as DataTable = con.GetSchema("COLUMNS")
Dim dr as DataRow
For Each dr in schema.Rows
Dim tablename as string = dr("TABLE_NAME").ToString()
if Not tablename.StartsWith("MSys") then
Console.WriteLine(dr("TABLE_NAME").ToString() + " " + dr("COLUMN_NAME").ToString())
End if
Next
End Using
Please note that the bang (!) syntax is not allowed in vb.net.
Also your code could work if you change
dbDt = dbcon.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Columns, New Object() _
{Nothing, Nothing, Nothing, Nothing})
and this line
frmMain.lstTables.Items.Add(dbDt.Rows(i)("COLUMN_NAME").ToString())

Resources