showing a sql coulmn data in a vb.net combobox - vb.net

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.

Related

VB.net Forecolor in every listview item

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

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

How to refresh form after selecting value from combobox

I would like to know if it is possible to refresh the current windows form I am at after selecting another value from the combo box in order to display the details of that item onto several other textboxes?
So my table looks like
table name : program
program_id program_name program_desc
1 T1 desc1
This is the code i am using atm
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "pathway"
Dim dr As SqlDataReader
Dim prognamedesc As String
Dim filetypetxt As String
Dim prognamecombo As String
Dim filetypecombo1 As String
Dim command As New SqlCommand
Dim querycommand As New SqlCommand
connection.Open()
'THIS SECTION LOADS DATA FROM THE TABLES'
Try
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "select program_name,filetype from program order by program_name; select * from filetype"
querycommand.Connection = connection
querycommand.CommandType = CommandType.Text
querycommand.CommandText = "select program_name,program_desc , filetype from program where program_name like" & FiletypeComboBox1.SelectedItem & ""
dr = command.ExecuteReader
While dr.Read()
prognamecombo = dr(0)
Program_nameComboBox.Items.Add(prognamecombo)
End While
dr.NextResult()
While dr.Read()
filetypecombo1 = dr(0)
FiletypeComboBox1.Items.Add(filetypecombo1)
FiletypeComboBox1.SelectedItem = filetypecombo1
End While
dr.NextResult()
While dr.Read()
filetypetxt = dr(0)
FiletypeLabel1.Text = filetypetxt
End While
dr.NextResult()
While dr.Read()
prognamedesc = dr(0)
Program_descTextBox.Text = prognamedesc
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
I was wondering if this is doable using the current code?
To implement this you have to do two things, First put all your code inside a method and call it something like RefreshForm()
public void RefreshForm()
{
// your code and binding goes here
}
The second step is by using selected index changed event over combobox you just call the method that includes all your binding code.

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub

Type Mismatch when combining two csv files in VB

I had my code working just fine, but when I generated new updated versions of the CSV files it suddenly errors out on me and gives me a type mismatch catch.
Here is the code that I have right now.
Dim A As String = "ADusers.csv"
Dim B As String = "MlnExp.csv"
Dim filePath As String = "C:\CSV"
Try
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (filePath) & "\;Extended Properties='text;HDR=Yes'"
Dim sSql As String = "SELECT *" _
& "FROM ([" & (B) & "] B LEFT JOIN [" & (A) & "] A ON B.EmployeeNumber = A.employeeID)"
Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString)
Dim Command As OleDb.OleDbCommand = New OleDb.OleDbCommand(sSql, conn)
Command.CommandType = CommandType.Text
conn.Open()
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sSql, conn)
Dim dt As DataTable = New DataTable
da.Fill(dt)
DataGrid1.DataSource = dt
DataGrid1.Update()
conn.Close()
lblStatus.Text = "CSV combined... Now saving to file."
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation)
End Try
Before it would go through, combine the two CSV files, and then display them in my datagrid. But now my catch is throwing back
Type mismatch in expression
i would check B.EmployeeNumber = A.employeeID
in both of your file one is a text value (left align) and the other is a a interger(right align)