add items from access to combobox vb.net - vb.net

I want to fill a combobox with items from ms access database.
here's my code..
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
conn.Open()
sqlQry = "SELECT * FROM Candidates where Position='President'"
cmd = New OleDbCommand(sqlQry, conn)
rdr = cmd.ExecuteReader
While rdr.Read()
ComboBox1.Items.Add(rdr("CandidateName").ToString())
End While
however the combobox won't fill up, but if i remove the "where Position ='President'" the code works, can someone help me i've been stuck here for hours.

you can try this i hope this work.
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn.Open()
Dim cm As New OleDbCommand("select * from Candidates where Position='President'", cn)
Dim dr As OleDbDataReader = cm.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr(1).ToString)
End While
dr.Close()
cn.Close()
End Sub

Related

fill datagridview based on combobox selected item which depends on another selected combobox from database

I am creating an add student windows form and it contains two comboboxes. the first one contains semester of the student and the second one contains the course code based on the value of semester. the problem I'm facing is that i also have a datagridview and i want to populate it with data of students contained in table of course code and as soon as i click semester combobox value of course code combobox changes, as soon as it changes, I want to load data of datagridview but it shows the error which basically is cannot convert datarows to string but when I use ComboBox1.ValueMember and load datagridview on clicking button it works fine. but when i load datagridview on combobox change it shows error.
this code works fine
Imports System.Data.OleDb
Public Class AddStudent
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Students.accdb")
Dim con1 As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Users.accdb")
Private Sub AddStudent_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.Open()
Dim cmd As New OleDbCommand("Select stud_roll From " + ComboBox1.SelectedValue + " where stud_roll = #roll1", con)
cmd.Parameters.AddWithValue("roll1", TextBox2.Text)
Dim myreader As OleDbDataReader = cmd.ExecuteReader
If myreader.Read() Then
con.Close()
MessageBox.Show("Student Inserted before")
Else
con.Close()
Dim cmd1 As New OleDbCommand("Insert into " + ComboBox1.SelectedValue + "(stud_roll,stud_name,date_of_birth,course,gender,mobile_no,semester) Values(#roll,#name,#dob,#course,#gender,#mobile,#semester)", con)
cmd1.Parameters.AddWithValue("roll", Convert.ToInt32(TextBox2.Text))
cmd1.Parameters.AddWithValue("name", TextBox1.Text)
cmd1.Parameters.AddWithValue("dob", DateTimePicker1.Value.Date)
cmd1.Parameters.AddWithValue("course", ComboBox1.SelectedValue)
cmd1.Parameters.AddWithValue("gender", ComboBox2.SelectedItem)
cmd1.Parameters.AddWithValue("mobile_no", MaskedTextBox1.Text)
cmd1.Parameters.AddWithValue("semester", Convert.ToInt32(ComboBox3.SelectedItem))
con.Open()
cmd1.ExecuteNonQuery()
con.Close()
MessageBox.Show("Records inserted successfully")
End If
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
Private Sub Label8_Click(sender As Object, e As EventArgs) Handles Label8.Click
AddTeacher.Show()
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
con1.Open()
Dim cmd As New OleDbCommand("Select course_code From courses Where semester= " + ComboBox3.SelectedItem + "", con1)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "course_code"
ComboBox1.ValueMember = "course_code"
con1.Close()
End Sub
Private Sub Label14_Click(sender As Object, e As EventArgs) Handles Label14.Click
Courses.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
End Class
when i load after combobox change like this, it shows error :- System.InvalidCastException: 'Operator '+' is not defined for string "Select stud_name, stud_roll From" and type 'DataRowView'.'
which is because of datarowview type conversion
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
please help me with this.
1. Make sure to give the controls meaningful names: it will make your life easier. "ComboBox1" is not a meaningful name ;)
2. Don't create a single instance of a database connection that is re-used: you are meant to create the connection object, use it, and then dispose of it. There are mechanisms behind the scenes to make this efficient (Connection Pooling). There is an example of how to do it in a previous answer of mine.
3. You don't need to open and close the connection for da.Fill(dt): it does it automatically.
4. Because ComboBox1.SelectedValue comes from a datatable, you will need to extract the column of that datarowview, something like:
Dim tableName = DirectCast(ComboBox1.SelectedItem, DataRowView).Row.Field(Of String)("course_code")
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From [" & tableName & "]", con)

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

returning select value using Visual Basic 2010 oleDB

I'm trying to read a excel cell with visual basic 2010 ( I'm really new to this) and I think I finally did it BUT I have no clue how to return the result.
It should end up in the clipboard or msgBox from there I'll find my way :D
I searched for two hours now but didnt find the solution... please help me
Thanks
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;extended properties=excel 8.0;"
cn.Open()
With cm
.Connection = cn
.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
.ExecuteNonQuery()
End With
cn.Close()
MsgBox(????)
End Sub
EDIT: her is the updated code. I get "Could not find installable ISAM
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;extended properties=excel 12.0;HDR=Yes"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:C20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
EDIT: That's what worked for me:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT Service FROM [ccs$] WHERE id='" & ComboBox1.SelectedItem & "'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
Welcome to SO. In the future you should show us all of your code. Since you tagged OleDB and vb.net, the following implements what you are trying to accomplish. I included the Form Class so the Imports statements could be shown, but you can just copy and paste the click event code after insuring you Class includes the Imports. Note, I have not tested this code but it should work. Let me know if you need clarification or additional help.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
' **EDIT**
con.ConnectionString = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

adding a value to my combo box using query

I'm trying to populate my combo box using the information in my database.. but I don't know the code for populating it. btw, I'm using vb windows form.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Dim cmd As SqlCommand = New SqlCommand("select distinct CompanyName from company ", con)
cmd.ExecuteReader()
con.Open()
While cmd.ExecuteReader.Read
End While
con.Close()
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Using Adp as new SqlDataAdapter("select distinct CompanyName from company", con)
Dim Dt as New DataTable
Adp.Fill(Dt)
ComboBox1.DataSource=Dt
ComboBox1.DisplayMember="CompanyName"
End Using
End Using
End Sub
Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Using cmd As New SqlCommand("select distinct CompanyName from company", cnn)
Try
cnn.Open()
Dim r = cmd.ExecuteReader
If r.HasRows Then
While r.Read
''add the items to the ComboBox
ComboBox1.Items.Add(r.GetString(0))
End While
End If
Catch ex As Exception
''handle the error
End Try
End Using
End Using