VB.net Forecolor in every listview item - vb.net

guys can you help me figure out how to put some forecolor in every listview item?
what I am trying to do is: I want to populate the listview with some forecolors in the items just like this
Example:
> ColumnHeader1 ColumnHeader2 ColumnHeader3
> Executive(W/Forecolor) texttexttext texttexttexttext
> Employee(Plain w/out FC) texttexttext texttexttexttext
here is my code:
Private Sub loadRemarks()
Try
jonsqlcon.Close()
jonsqlcon.ConnectionString = dllConstring
jonsqlcon.Open()
Dim selStaff As New SqlDataAdapter("SELECT * FROM StaffMember WHERE Staff_IDNo ='" & Notification.lblStaffID.Text & "'", jonsqlcon)
Dim setStaff As New DataSet
Dim accLvl As String
selStaff.Fill(setStaff)
accLvl = setStaff.Tables(0).DefaultView.Item(0).Item("AccessLVL").ToString
If accLvl = "2" Then
ListView1.ForeColor = Color.Aqua
End If
Dim loadChat As New SqlCommand("SELECT * FROM RemarksConvo WHERE Application_ID = '" & ClientAccountStatusViewer.txtClientID.Text & "' AND Room ='" & lvlStorage.Text & "'", jonsqlcon)
reader = loadChat.ExecuteReader
ListView1.Items.Clear()
Do While reader.Read = True
list = ListView1.Items.Add(reader(3).ToString)
list.SubItems.Add(reader(4).ToString)
list.SubItems.Add(reader(5).ToString)
list.SubItems.Add(reader(6).ToString)
Loop
Catch ex As Exception
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub

First thing you should worry is about the Sql Injection problem of your code. Do not use string concatenation to build a query text but always a parameterized text. Not only your command is more clear but there is no way that an hacker could tamper your text to wreak havoc with your database.
Second. You can bring the information about the level of your remark's author by executing a join between the two tables. The field Staff_IDNo in both tables links the records from the remarks to the table with the info about the level of the remark's author
Finally, a ListViewItem (the object returned by ListView.Items.Add) supports the ForeColor property and you can simply set the color row by row while you add items to your listview
Dim loadChat As New SqlCommand("SELECT r.*, s.AccessLVL FROM RemarksConvo r
JOIN StaffMember s ON s.Staff_IDNo = r.Staff_IDNo
WHERE r.Application_ID = #appId
AND r.Room = #room", jonsqlcon)
loadChat.Parameters.Add("#appId", SqlDbType.NVarChar).Value = ClientAccountStatusViewer.txtClientID.Text
loadChat.Parameters.Add("#room", SqlDbType.NVarChar).Value = lvlStorage.Text)
reader = loadChat.ExecuteReader
ListView1.Items.Clear()
Do While reader.Read
list = ListView1.Items.Add(reader(3).ToString)
list.ForeColor = If(reader("AccessLvl").ToString = "2", Color.Acqua, SystemColors.WindowText)
list.SubItems.Add(reader(4).ToString)
list.SubItems.Add(reader(5).ToString)
list.SubItems.Add(reader(6).ToString)
Loop

Related

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

Issues with deleting records and data reading using vb.net

I'm very new to programming and I'm at the very end of my first vb.net programming assignment but I can't figure this last part out.
The program is a small address book with database back-end, my problem occurs when I delete a contacts record.
The data record being read is based off the contacts primary key, when I delete a contact record the next contact record moves up but every record below it doesn't read correctly.
I have a feeling this occurs because my code only reads the primary keys in sequential order, but I'm not sure how to go about changing it to make it work correctly.
Here's the code that relates to it reading the data when i select the record in a listview.
Private Sub ListView1_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
Dim command As MySqlCommand = Nothing
Dim reader As MySqlDataReader
Dim query As String = "SELECT * FROM contacts WHERE id= '" & ListView1.FocusedItem.Index + 1 & "'"
Try
connection.Open()
command = New MySqlCommand(query, connection)
reader = command.ExecuteReader
While reader.Read
txtFirstName.Text = reader.GetString("first_name")
txtSurname.Text = reader.GetString("surname")
txtHouseNo.Text = reader.GetString("house_number")
txtStreet.Text = reader.GetString("street")
txtSuburb.Text = reader.GetString("suburb")
cboState.Text = reader.GetString("state")
txtPhone.Text = reader.GetString("phone")
txtMobile.Text = reader.GetString("mobile")
txtWork.Text = reader.GetString("work")
txtEmail.Text = reader.GetString("email")
txtNotes.Text = reader.GetString("notes")
txtid.Text = reader.GetString("id")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
connection.Close()
command.Dispose()
End Try
Call txtEnable()
End Sub
And here's how I load the contacts to the listview
Private Sub loadcontacts()
Dim command As MySqlCommand = Nothing
Dim listquery As String = "SELECT * FROM contacts ORDER BY id"
Dim reader As MySqlDataReader = Nothing
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
command = New MySqlCommand(listquery, connection)
reader = command.ExecuteReader()
command.CommandText = listquery
With ListView1
.Columns.Add("Name", 220, HorizontalAlignment.Left)
End With
ListView with the data
While reader.Read
Dim ls As New ListViewItem(reader.Item("first_name").ToString() & " " & reader.Item("surname").ToString)
ListView1.Items.Add(ls)
End While
Catch ex As MySqlException
Finally
connection.Close()
command.Dispose()
End Try
End Sub
Thanks for any help.
After you delete a record, clear and reload your list.
For anyone that has a similar problem I figured it out.
Steve helped me get on the right track here so thank you.
I added the ID (primary key) subitem like this:
While reader.Read
Dim ls As New ListViewItem(reader.Item("first_name").ToString() & " " & reader.Item("surname").ToString)
ls.SubItems.Add(reader.Item("id").ToString)
ListView1.Items.Add(ls)
then in the listview focused item I made the query like this:
Dim query As String = "SELECT * FROM contacts WHERE id = '" & ListView1.FocusedItem.SubItems(1).Text & "'"
Now save, update, and delete work with primary key ID reading in the correct order. Thanks for the help and I hope this helps out someone in the future

showing a sql coulmn data in a vb.net combobox

I want to show all the data in a specific column in one combobox and my code is just showing the last data in the column here is the code i am using
Dim connectionstring As String = "Data Source=localhost\SQLEXPRESS;InitialCatalog=Enginee;Integrated Security=True"
Try
Dim connection As New SqlClient.SqlConnection(ConnectionString)
Dim sqlquery As String
connection.Open()
MessageBox.Show("Open")
sqlquery = " Select PROJECT.PROJECT_CODE,PROJECT.PROJECT_NAME From PROJECT INNER JOIN ENGINEERS on ENGINEERS.ENGINEER_ID = ENGINEERS.ENGINEER_ID where ENGINEERS.FNAME = '" & Sign_In.TextBox1.Text & "' "
Dim selectcommand As New SqlClient.SqlCommand(sqlquery, connection)
Dim reader As SqlClient.SqlDataReader = selectcommand.ExecuteReader
Dim test As Boolean = reader.Read
While test = True
ComboBox1.Text = reader(0)
TextBox1.Text = reader(1)
test = reader.Read
End While
Catch ex As Exception
MessageBox.Show("Failed")
End Try
Instead of setting the .text of the ComboBox add the item.
ComboBox1.Items.Add(reader(0));
Setting the Text value will just set what the current item is, not adding them to the dropdown list.

How to Trigger Code with ComboBox Change Event

I have a created a database containing historical stock prices. On my form I have two comboboxes, ComboBox_Ticker and ComboBox_Date. When these comboboxes are filled I want to check the database and see if the respective data exists in the database. If it does I want to change the text of a label called Label_If_Present to "In Database".
My problem occurs with the change event. I want all of this to happen once I change the data in the textboxes. I have tried both the .TextChanged and .LostFocus events. The '.TextChanged' triggers the code to early and throws and error in my SQL command statement. The `.LostFocus' event doesn't do trigger my code at all.
Here is my current code:
Public databaseName As String = "G:\Programming\Nordeen Investing 3\NI3 Database.mdb"
Public con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
Public tblName As String = "Historical_Stock_Prices"
Private Sub Change_Labels(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox_Ticker.TextChanged, ComboBox_Date.TextChanged
con.Close()
Dim dr As OleDbDataReader
con.Open()
If (File.Exists(databaseName)) Then
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = con.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
Else
Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & tblName & " WHERE Ticker = '" & ComboBox_Ticker.Text & "' " & " AND Date1 = '" & ComboBox_Date.Text & "'", con)
dr = cmd2.ExecuteReader
If dr.Read() = 0 Then
'If record does not exist
Label_If_Present.Text = ""
Else
Label_If_Present.Text = "In Database"
End If
con.Close()
End If
Else
End If
End Sub
I have successfully implemented this concept on other forms within my project. This one is slightly different and I can't figure out why I can't get this one to work.
Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value.
Then check to see that both comboboxes have values selected. Something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then

Getting selected listbox items values to display in another listbox using vb 2008

I have a form with a 2 listboxes. Here, listbox1 is populated with names of actors and actresses. If a name is selected from listbox1, listbox2 should show the title(s) of movie(s) where that name is involved. If another name is selected, listbox2 will show title(s) of movie(s) that 2 name is involved.
Call Connect()
With Me
STRSQL = "select mTitle from selectmovie where cName = '" & lstNames.SelectedItem & "'"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = myCmd
myAdptr.Fill(myDataTable)
lstTitle.DisplayMember = "mTitle"
lstTitle.ValueMember = "mTitle"
If myDataTable.Rows.Count > 0 Then
For i As Integer = 0 To myDataTable.Rows.Count - 1
lstTitle.Items.Add(myDataTable.Rows(i)("mTitle"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
There's no error. When I select 1 item the result is correct but it leaves many space..here the screen shot of my form: http://www.flickr.com/photos/92925726#N06/8445945758/in/photostream/
The output becomes worse when I selected actor3: http://www.flickr.com/photos/92925726#N06/8445945724/in/photostream/
Your main problem seems to be that you do not clear your lstTitle control before re-loading it with the new selection. Therefore, each time you select a new name, it will add all the titles for that name to the existing list of titles that are already loaded. Also, instead of using an integer to iterate all the indexes, it is easier to just use a For Each loop:
lstTitle.Items.Clear()
For Each row As DataRow In myDataTable.Rows
lstTitle.Items.Add(row("mTitle"))
Next
However, I must also mention that you really should also be using a parameter in your query rather than dynamically building the SQL statement like that, for instance:
myCmd.CommandText = "select mTitle from selectmovie where cName = #name"
myCmd.Parameters.AddWithValue("name", lstNames.SelectedItem)
To select all the movies where all of the multiple selected actors are involved, you would need to add an additional condition to your where clause for each actor, for instance:
Dim builder As New StringBuilder()
builder.Append("select distinct mTitle from selectmovie where ")
For i As Integer = 0 to lstNames.SelectedItems.Count - 1
Dim parameterName As String = "#name" & i.ToString()
If i <> 0 Then
builder.Append("and ")
End If
builder.Append(parameterName)
builder.Append(" in (select cName from selectmovie where mTitle = m.mTitle) ")
myCmd.Parameters.AddWithValue(parameterName, lstNames.SelectedItems(i))
Next
myCmd.CommandText = builder.ToString()