I have 3 text boxes and based on Customer Name suggestion other 2 boxes should be auto filled
I am new to database so I am finding codes on internet and trying to implement it but it
is not working. So please help me with this.
I am working in for Windows Form Application in visual basic.
Private Sub AutoComplete()
'sql = "Select * FROM Table1 where CustomerName='" & custnm.Text & "'"
com = New OleDbCommand(sql, con)
reader = com.ExecuteReader()
Dim autoComp As New AutoCompleteStringCollection()
While reader.Read()
autoComp.Add(reader("CustomerName"))
autoComp.Add(reader("ContactNO"))
End While
reader.Close()
custnm.AutoCompleteMode = AutoCompleteMode.Suggest
custnm.AutoCompleteSource = AutoCompleteSource.CustomSource
custnm.AutoCompleteCustomSource = autoComp
contactno.AutoCompleteMode = AutoCompleteMode.Suggest
contactno.AutoCompleteSource = AutoCompleteSource.CustomSource
contactno.AutoCompleteCustomSource = autoComp
wcontno.AutoCompleteMode = AutoCompleteMode.Suggest
wcontno.AutoCompleteSource = AutoCompleteSource.CustomSource
wcontno.AutoCompleteCustomSource = autoComp
End Sub
This is only a partial solution to straighten out your database code. It is too much code to put in a comment.
Keep your database objects local so you can control when they are closed and disposed. Objects that expose a .Dispose method may have unmanaged resources that need to be released. A Using...End Using block will handle this for you even if there is and error.
Always use Parameters to avoid sql injection which can damage your database. Also it makes the sql string easier to write. You will need to check your database for the proper datatype because I had to guess.
A DataReader uses an open connection until it is done. You don't want to hold your connection open while you use the data so I chose a DataTable. Just load it and pass it off to where you want to use it. The connection and command are closed and disposed.
I wasn't sure why you combined the data in a single AutoCompleteStringCollection. It seems that one for each combo box would be better. They are form level variables so you can used them in another method to attach to a combo box.
I think you need to look into BindingSource and BindingNavigator to sync the combo boxes.
Private Function GetData() As DataTable
Dim dt As New DataTable
Using con As New OleDbConnection("Your connection string"),
com As New OleDbCommand("Select * FROM Table1 where CustomerName= #Name;", con)
com.Parameters.Add("#Name", OleDbType.VarChar).Value = custnm.Text
con.Open()
dt.Load(com.ExecuteReader)
End Using
Return dt
End Function
Private autoCompName As New AutoCompleteStringCollection()
Private autoCompNO As New AutoCompleteStringCollection()
Private Sub FillAutoCompleteCollection()
Dim dt = GetData()
For Each row As DataRow In dt.Rows
autoCompName.Add(row("CustomerName").ToString)
autoCompNO.Add(row("ContractNO").ToString)
Next
End Sub
Related
I am learning visual basic and OOP on the fly.
This piece of code displays the query results to a combo box on a form...
Dim c = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Dim daDogs As New SqlDataAdapter ("select dog_type from humane_society with(nolock)",c)
Dim dtdogs As New DataTable
dadogs.Fill(dtdogs)
cboDogs.DataSource = dtdogs
cboDogs.DisplayMember = "dog_type"
when I change it to use a Using block, the combo box is blank
I think it is a scope issue, but I don't know how to fix it. Any productive suggestions would be greatly appreciated. Thanks!
Dim c = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Using cDog As New SqlConnection(c)
Using cmd As New SqlCommand("select dog_type from humane_society with(nolock)",cDog)
cmd.CommandType = commandtype.Text
Using daDogs As New SqlDataAdapter(cmd)
Using dtDogs As New Datatable`enter code here`
daDogs.Fill(dtDogs)
' MsgBox(dtMunic.Rows(500).Field(of string)(0))
cboDogs.DataSource = dtDogs
cboDogs.DisplayMember = "dog_type"
End Using
End Using
End Using
End Using
Not sure what that message box is doing in your code. Remember that a message box halts the code until the user responds. You connection, among other things, is open while the code waits.
You are correct that items declared in a block are scoped to that block.
I have separated your database code from your user interface code.
You can save using blocks by adding a comma and combining more than one object in the block. Behaves the same, just makes the code a bit easier to read.
Private ConStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString() '"Your connection string"
Private Function GetDogData() As DataTable
Dim dt As New DataTable
Using cDog As New SqlConnection(ConStr),
cmd As New SqlCommand("select dog_type from humane_society with(nolock)", cDog)
cDog.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dtDogs = GetDogData()
cboDogs.DataSource = dtDogs
cboDogs.DisplayMember = "dog_type"
End Sub
how can i populate multiple table into multiple DataGridview?
for example i have 3 tables which is table1, table2 and table3, and in my form i have 3 dataGridView with name of dataGridView1, dataGridView2 and dataGridView3. i found this solution Updating an Access Database via a DataGridView Using OLEDB in VB.NET as a result of my code.
function loadDatabaseDataToGridView
Dim msAccessFilePath As String
Dim con As New OleDbConnection
Dim dataTable, dataTable2, dataTable3, dataTable4 As New DataTable
Dim olebDataAdapter As New OleDbDataAdapter
Dim da As New OleDbDataAdapter
Dim dataSet As New DataSet
Private Sub loadDatabaseDataToGridView()
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & msAccessFilePath
dataSet.Tables.Add(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table1", con)
olebDataAdapter.Fill(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table2", con)
olebDataAdapter.Fill(dataTable2)
olebDataAdapter = New OleDbDataAdapter("Select * from table3", con)
olebDataAdapter.Fill(dataTable3)
DataGridView1.DataSource = dataTable.DefaultView
DataGridView2.DataSource = dataTable2.DefaultView
DataGridView3.DataSource = dataTable3.DefaultView
Dim cb = New OleDbCommandBuilder(olebDataAdapter)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
MessageBox.Show("Successfull")
Catch ex As Exception
MessageBox.Show("Failed")
con.Close()
End Try
con.Close()
End Sub
function SaveChanges
'Perform this on Button Save is Click
Private Sub saveChanges()
olebDataAdapter.Update(dataSet)
End Sub
This code is working as excpected, it is populating the data from MS Access file but when i clicked the button save to save the changes on edited data, an error has occurred.
THE ERROR:
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
anyone does know how to properly implement of what i am trying to achieve? Thank You Very Much!!!
Each DataAdapter object only has a single UpdateCommand, so you'll need one for each data table. If it runs the update command and no rows are updated (because the update command is actually for a table that you haven't changed) then you'll get the Concurrency Violatation.
It actually gets more complicated than this if your tables are related as the order that inserts, updates and deletions occur can be critical.
If you create a Strongly Typed Dataset it generates designer code that includes a TableAdapterManager class and all of the required data adapters. It might be worth playing around with this just so that you can see how the generated code works.
Just a note, the 'Concurrency violation' exception is actually there so that you can design an update command that will only succeed if the contents of the record in the database match the data held locally (to prevent you from overwriting another user's changes). Search for Optimistic Locking for more details.
In my application I create a function that allow the user to change the settings of the app. This settings are stored into a table 'cause there's a lot of records. Anyway, the problem's that if the settings isn't valorized yet, when the application start and load the settings from the table take of course a null GUID field and the message:
GUID format not recognized
appear. A code explaination:
Sub LoadSettings()
Using dbCon As MySqlConnection = establishConnection()
Try
dbCon.Open()
Dim MysqlCommand = New MySqlCommand("SELECT * FROM settings", dbCon)
Dim reader = MysqlCommand.ExecuteReader
For Each row In reader
Select Case row(2)
Case "company_name"
Setting.name.Text = row(3)
Case "company_email"
Setting.email.Text = row(3)
...
End Select
Next
End Sub
This function is called when the settings form is opened. If the settings aren't inserted yet, I get a message of bad format. I want to know how I can avoid this message.
You are not using the DataReader correctly. Consider this code:
Dim reader = MysqlCommand.ExecuteReader
For Each row In reader
... something
Next
MysqlCommand.ExecuteReader returns a DataReader object, but it is not - nor does it contain - a row collection you can iterate. If you hold the mouse over row you should see that it is a Data.Common.DataRecordInternal object which does have an Item property but a reference like row(2) will only compile with Option Strict Off.
Used correctly, when you Read a row the data in that internal object is available via the indexer (Item) and the various Getxxxxx() methods. This just prints the Id and Name from a table in a loop. I cant quite tell what you are trying to do with your results...it sort of looks like a Name/Value pair type thing maybe.
Dim SQL = "SELECT * FROM Demo"
Using dbcon = GetMySQLConnection(),
cmd As MySqlCommand = New MySqlCommand(SQL, dbcon)
dbcon.Open()
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
Do While rdr.Read()
Console.WriteLine("{0} - {1}", rdr("Id").ToString, rdr("Name").ToString)
Loop
End If
End Using ' dispose of reader
End Using ' dispose of Connection AND command object
Alternatively, you could fill a DataTable and iterate the rows in that. Seems 6:5 and pick-em whether that would gain anything.
Note also that the Connection, Command and DataReader objects are properly disposed of when we are done using them.
I am accessing data from Access MDB file using my application developed in VB .net 2010.
I want to get values from a particular table-column to be populated in a Combo Box dropdown.
I followed a similar thread # C# Adding data to combo-box from MS Access table but as the code is in C#, I was not able to successfully implement it. And reverted back to my previous code.
Because the Table will be updated by another application as well, every time I use my utility I need to get the latest data from that table. Hence I would like to have a feature that could get all available id from table.
Below is what I have been trying to do..
'below declared at class level.
' Dim cnnOLEDB As New OleDbConnection
' Dim cmdOLEDB As New OleDbCommand
cnnOLEDB.Open()
cmdOLEDB.CommandText = "select unique_id from tag_data"
cmdOLEDB.Connection = cnnOLEDB
Dim rdrOLEDB2 As OleDbDataReader = cmdOLEDB.ExecuteReader
If rdrOLEDB2.Read = True Then
TagComboBox1.DataSource = rdrOLEDB2.Item(0).ToString
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If
rdrOLEDB2.Dispose()
rdrOLEDB2.Close()
cnnOLEDB.Close()
I would recommend filling a DataTable with your query. Then you can set the DataSource of the combobox, ValueMember & the DisplayMember.
Dim dt As New DataTable
Dim query As String = "select unique_id from tag_data"
Using connection As New OleDbConnection("your connection string")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
TagComboBox1.DataSource = dt
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If
I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.
On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.
Public Sub LoadWorkItem()
' Load the data.
' Select records.
Dim oWorkItem As WorkItem = New WorkItem()
Dim conn As New OleDbConnection
Dim data_reader As OleDbDataReader
conn = oWorkItem.GetDbConnection()
Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
data_reader = cmd.ExecuteReader()
'ListBox1.Items.Clear()
If data_reader.HasRows = True Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
Loop
End If
data_reader.Close()
data_reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
End Sub
How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you
To poulate your ListBox, do this...
ListBox1.Item.Clear()
If data_reader.HasRows Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
Loop
End If
As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...
Using conn As OleDbConnection = oWorkItem.GetDbConnection()
' Execute SQL and populate list...
End Using
The above code assures that your connection will be closed.
Then, turn on Option Strict and Option Explicit. This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.
Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design. Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.
Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
Your core method should then ask a "data access" method for data.
The "data access" method should make the call to the database.
Happy coding.
Update: You can find excellent info about n-Tier architecture on MSDN. A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects.
Imports System.Data.SqlClient 'Reference The Sql Client
Public Class Form1
''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work
Dim connString As String = "Data
Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = connString
dsDIV = New DataSet
' Select all Fields and order by ID or Replace * with name of Field
daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
'*** Define command builder to generate the necessary SQL
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
ListBox1.DataSource = tblDIV
ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub