ComboBox connection with database - sql

I am trying to link the combobox with my database column "name", for this purpose i am watching a tutorial from youtube. Everything is going smooth but now I am having problem with connecting it with a combobox. I am new to VB.Net, so please guide me.
Here is my code:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\zeeshan\documents\visual studio 2013\Projects\Tutorials\Tutorials\Register.mdf"
Dim READER As SqlDataReader
Try
con.Open()
Dim Query As String
Query = "select * from dbo.edata"
cmd = New SqlCommand(Query, con)
READER = cmd.ExecuteReader
While READER.Read
Dim sName = READER.GetString("name")
ComboBox1.Items.Add(sName)
End While
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
I have attached the error pic as well. This code is working fine in video tutorial but I m having problem using it.

datatable dt= cmd.ExecuteReader
if(dt.rows.count>0)
{
foreach(Datarow dr in dt.rows)
{
ComboBox1.Items.Add(dt.Rows[0]["Name"].ToString());
}
}

Use index column
While READER.Read
Dim sName = READER.GetString(1)
ComboBox1.Items.Add(sName)
End While

Related

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

Load data into DataGridView from sql server in vb

Loading data from SQL server into datagridview but Warning 1 Variable 'dtApplicantLists' is used before it has been assigned a value. A null reference exception could result in runtime. green underline at dtApplicantLists.Load(reader)
Any help, please...
Private Function GetList() As DataTable
Dim dtApplicantLists As DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmmd As New SqlCommand("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants", conn)
conn.Open()
Dim reader As SqlDataReader = cmmd.ExecuteReader()
dtApplicantLists.Load(reader)
End Using
End Using
Return dtApplicantLists
End Function
You need to call dtApplicantLists = New DataTable - currently it is null (or Nothing in VB).
Using ... End Using Method will guarantee you won't need to worry about warnings like this one you got, as obviously demonstrated in your Code.
Private Function GetList() As DataTable
Dim SqlStr As String =
("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants")
Using dtApplicantLists As DataTable = New DataTable
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbx").ConnectionString),
Cmd As New SqlCommand(SqlStr, conn)
conn.Open()
Using Reader As SqlDataReader = Cmd.ExecuteReader
dtApplicantLists.Load(Reader)
End Using
End Using
Return dtApplicantLists
End Using
End Function
You can do it this way.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
See the link below for some other similar, but slightly different options.
http://vb.net-informations.com/dataadapter/dataadapter-datagridview-sqlserver.htm

While dataReader.Read() not executing

The code executes everything but the While dataReader.Read() loop and I have no idea why. No errors are coming up, it just doesn't actually read the data with the data reader. Many thanks for any help received.
Private Sub BtnFind_Click(sender As Object, e As EventArgs) Handles BtnFind.Click
Dim cmd As OleDbCommand
Dim myConnection As OleDbConnection
Dim text As String = txtTeacherID.Text
Dim dataReader As OleDbDataReader
Try
'selects the information from the row where the column has the teacher ID
myConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\My Documents\database.accdb")
myConnection.Open()
cmd = New OleDbCommand("SELECT * FROM [TMessages] WHERE TeacherID = '" & text & "'", myConnection)
dataReader = cmd.ExecuteReader
While dataReader.Read()
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
MsgBox("reading")
End While
Catch
MsgBox("Error occured")
End Try
dataReader.Close()
myConnection.Close()
End Sub
As pointed in my comment, you are only reading the same value 3 times
lstItems.Items.Add(dataReader(0))
And the read value may be in blank, try to use your reader to read all the values recieved in the dataReader thought a loop and check all the values.
for i = 0 to dataReader.FieldCount

Reading OleDb records into TextBox using ComboBox VB.NET

I'm new to programming. What i'm trying to accomplish is to fill in 9 textboxes in VB.NET, reading access table TblKlanten, using a combobox (CbbNaamfirma). I cannot get this to work for the life of me; i've been searching for 6 hours for this simple thing. Can any of you help me out? I've read numerous threads on SO.com like this and they all just won't work for me.
Code i have now:
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim Connection As New OleDb.OleDbConnection
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Application.StartupPath & "\Database.accdb.'"
Try
Connection.Open()
Dim query As String
query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ' " & CbbNaamfirma.Text & " ' "
Dim cmd As New OleDbCommand(query, Connection)
Dim Reader As OleDbDataReader = cmd.ExecuteReader
Reader = cmd.ExecuteReader
While Reader.Read
TxtAdresprev.Text = Reader.GetString("Adres")
End While
Connection.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Finally
Connection.Dispose()
End Try
End Sub
Thank you in advance. Hope that code block turned out alright?
The first thing to change is the reading from the database using a parameterized query. Notice that your code cannot find anything because you add a space before and after the value of the combobox.
Then you need to start employing the using statement around the disposable objects to ensure a proper closing and disposing
Finally the GetString method from the OleDbDataReader wants a numeric index inside the returned list of fields, not the name of the field
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Application.StartupPath & "\Database.accdb"
Dim query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ?"
Using Connection = New OleDb.OleDbConnection(cnString)
Using cmd = New OleDbCommand(query, Connection)
Try
Connection.Open()
cmd.Parameters.AddWithValue("#p1", CbbNaamfirma.Text)
Using Reader = cmd.ExecuteReader
While Reader.Read
Dim posAdres = Reader.GetOrdinal("Adres")
TxtAdresprev.Text = Reader.GetString(posAdres)
.... other text boxes for other fields here.....
End While
End Using
Catch ex As OleDbException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Also your connection string seems to be wrong. No need of quotation and that stray point after the fielname is wrong

Checking a PIN number is correct according to it's card number

I'm currently working on an assignment for college that I'm really stuck on. I have to create an application to simulate an ATM machine using Visual Basic 2010. I'm currently stuck trying to check whether the PIN number entered in the text box is correct for the card number selected in the combo box. If the user enters the PIN incorrectly three times, the card is confiscated. I am getting an error message at the moment saying "Object variable or With block variable not set". Below is the code I have written:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount As Integer
Dim ATMCardsBindingSource As New BindingSource
Dim SqlCommandCheckPIN As New OleDbCommand
Dim SqlCommandConfiscate As New OleDbCommand
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
Try
Me.connectionBG.Open()
Dim PIN As String
Dim cardNo As String
PIN = Me.txtPIN.Text
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandCheckPIN.Parameters("#PIN").Value = PIN
Me.SqlCommandCheckPIN.Parameters("#cardNumber").Value = cardNo
Dim dr As OleDbDataReader = Me.SqlCommandCheckPIN.ExecuteReader()
If dr.HasRows And pinErrorCount <= 2 Then
My.Forms.Menu.ShowDialog()
dr.Close()
pinErrorCount = 0
txtPIN.Text = ""
ElseIf pinErrorCount = 2 Then
dr.Close()
MessageBox.Show("PIN Entered Incorrectly Three Times Card Now Confiscated", "Card Taken", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandConfiscate.Parameters("#cardNumber").Value = cardNo
Me.SqlCommandConfiscate.ExecuteNonQuery()
Else
pinErrorCount = pinErrorCount + 1
MessageBox.Show("Incorrect PIN Please Try Again.", "Incorrect PIN", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtPIN.Text = ""
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Me.connectionBG.Close()
End Try
End Sub
End Class
Updated code below:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber, commandPinNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount, cardNumber, PIN As Integer
Dim oForm As Menu
Dim userInput As String
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
commandPinNumber.Connection = connectionBG
commandPinNumber.CommandType = CommandType.Text
commandPinNumber.CommandText = "SELECT PIN FROM ATMCards WHERE cardNumber = ?"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
cardNumber = Convert.ToInt16(cmbCardNumber.Text)
commandPinNumber.Parameters.Add(New OleDbParameter())
commandPinNumber.Parameters(0).Value = cardNumber
Try
connectionBG.Open()
dr = commandPinNumber.ExecuteReader()
While dr.Read()
PIN = dr.Item("PIN").ToString
End While
dr.Close()
If PIN = userInput Then
MsgBox("Correct PIN")
Else
MsgBox("Incorrect PIN")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub txtPIN_TextChanged(sender As Object, e As EventArgs) Handles txtPIN.TextChanged
userInput = txtPIN.Text
End Sub
End Class
OleDBCOmmand objects are typically used in a more disposable way than as module level variables. In order to work, they also need a SQL string and a Connection object associated with them. Ex:
Dim sql As String = "SELECT etc etc etc WHERE something = ?"
Using cmd As New OleDbCommand(Sql, dbCon)
cmd.Parameters.AddWithValue("#p1", myVar)
cmd.Parameters.AddWithValue("#p2", myVar)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
' do something interesting
End If
End Using
Here, both the SQL and DB Connection are associated with the Command Object when it is created. The Using block assures it is properly disposed of when we are done with it.
Also, OleDbCommand objects do not support named parameters. Usually, it just ignores them. The right way for Paramters is shown (ie AddWithValue) where you replace each ? placeholder in the SQL string in order with the actual value. Do be sure the data type matches. If PIN is a number, you must add a number, not Text.
For the SQL, you are testing the PIN entered against a card number, so those are the param values. Depending on how you construct the SQL you can either see if the PIN in the DB matches the one they gave OR just see if you get any rows back.