Combobox population does not appear in DataGridView in vb.net - vb.net

Combobox population does not appear in DataGridView because of the function of DataTable.
below link the previous code running normally with the combobox population.
please recommend the best solution.
I have also coded in my post so it doesn't miss communication
Thanks
link previous post
Private _dt As DataTable
'update code PopulateComboBox in form load
Public Sub New()
If Me.IsInDesignMode() Then
Return
End If
InitializeComponent()
Me.PopulateComboBox()
fillDataGridView1()
End Sub
Private Function GetAndFillDataTable() As DataTable
Dim dt As New DataTable()
Dim query As String = "SELECT NOD,ITM,CIA,DPR,QTY FROM RSD WHERE QTY > 0 AND PNM=#PNM"
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
da.Fill(dt)
da.Dispose()
Dim totalColumn As New DataColumn()
totalColumn.DataType = System.Type.GetType("System.Double")
totalColumn.ColumnName = "Total"
totalColumn.Expression = "[CIA]*[QTY]*(1-[DPR]/100)"
dt.Columns.Add(totalColumn)
Return dt
End Using
End Using
End Using
End Function
Private Sub FillDataGridView1()
If (_dt Is Nothing) Then
_dt = GetAndFillDataTable()
End If
grid.DataSource = _dt
grid.Refresh()
End Sub
Private Sub PopulateComboBox()
Dim dt As New DataTable()
Dim query As String = "SELECT DISTINCT PNM FROM RSD UNION SELECT DISTINCT PNM FROM RSG ORDER BY PNM"
Try
dt = New DataTable
Using con As OleDbConnection = New OleDbConnection(GetConnectionString)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
'update code combobox selectionchangecommited for fillDataGridView1
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
fillDataGridView1()
End Sub

You are setting your datasource = _dt in PopulateComboBox however the data table you built in your function is called dt.

Related

Why is my combobox not displaying data after being chosen

I have 2 combo boxes that are linked together, In the parent combo box, RoomT Type after a value is selected it does not allow me to reselect to a different value. Also if anyone would be so kind and tell me how i could use the primary key of the selected value from the combo box in SQL queries.
Here is what I got :
Private Sub FrmBookings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con1 As New SQLiteConnection(ConStr)
Using com As New SQLiteCommand("Select CustomerID, fname FROM customers Left JOIN BOOKING ON booking.BCustomerID = customers.customerID where booking.BookingID is null", con1)
con1.Open()
Dim dt As New DataTable()
dt.Load(com.ExecuteReader)
cmbCustomerData.DataSource = dt
cmbCustomerData.DisplayMember = "fname"
cmbCustomerData.ValueMember = "CustomerID"
End Using
End Using
Using con1 As New SQLiteConnection(ConStr)
Using da As New SQLiteDataAdapter("Select RoomTypeName, RoomTypeID FROM RoomType", con1)
Dim dt As New DataTable()
da.Fill(dt)
cmbRoomType.Items.Clear()
For Each row As DataRow In dt.Rows
cmbRoomType.Items.Add(row("roomTypeName").ToString)
Next
End Using
End Using
End Sub
Private Sub CmbRoomType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbRoomType.SelectedIndexChanged
'clear dt
cmbRoomType.Items.Clear()
Using con1 As New SQLiteConnection(ConStr)
Using da As New SQLiteDataAdapter("Select RoomNumber, RoomID FROM Rooms INNER JOIN RoomType ON roomtype.roomtypeid = rooms.rRoomTypeID WHERE roomtype.roomtypename LIKE '" & cmbRoomType.Text & "'", con1)
Dim dt As New DataTable()
da.Fill(dt)
cmbRoomNumber.Items.Clear()
For Each AB As DataRow In dt.Rows
cmbRoomNumber.Items.Add(AB("RoomNumber").ToString())
Next
End Using
End Using
End Sub
Event procedures should contain very little code. Certainly not data access code. DO NOT update the user interface when a connection is open. If you separate your user interface code from your data access code you will have a much easier time debugging and correcting your code. Try to keep methods doing just a single task clearly indicated by the method name.
Private ConStr As String = "Data Source=dbNEAProject.db"
Private Sub FrmBookings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillCustomerDataCombo()
FillRoomTypeCombo()
End Sub
Private Sub FillCustomerDataCombo()
Dim dt = GetCustomerData()
cmbCustomerData.DataSource = dt
cmbCustomerData.DisplayMember = "fname"
cmbCustomerData.ValueMember = "CustomerID"
End Sub
Private Function GetCustomerData() As DataTable
Dim dt As New DataTable()
Using con1 As New SQLiteConnection(ConStr)
Using com As New SQLiteCommand("Select CustomerID, fname FROM customers Left JOIN BOOKING ON booking.BCustomerID = customers.customerID where booking.BookingID is null", con1)
con1.Open()
dt.Load(com.ExecuteReader)
End Using
End Using
Return dt
End Function
Private Sub FillRoomTypeCombo()
Dim dt = GetRoomTypeData()
cmbRoomType.Items.Clear()
cmbRoomType.DisplayMember = "RoomTypeName"
cmbRoomType.ValueMember = "RoomTypeID"
CmbRoomType.DataSource = dt
End Sub
Private Function GetRoomTypeData() As DataTable
Dim dt As New DataTable()
Using con1 As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand("Select RoomTypeName, RoomTypeID FROM RoomType", con1)
con1.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub CmbRoomType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbRoomType.SelectedIndexChanged
Dim dt = GetRoomsOfSelectedType(cmbRoomType.Text)
cmbRoomNumber.Items.Clear()
For Each AB As DataRow In dt.Rows
cmbRoomNumber.Items.Add(AB("RoomNumber").ToString())
Next
End Sub
Private Function GetRoomsOfSelectedType(type As String) As DataTable
Dim dt As New DataTable()
Using con1 As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand("Select RoomNumber, RoomID FROM Rooms INNER JOIN RoomType ON roomtype.roomtypeid = rooms.rRoomTypeID WHERE roomtype.roomtypename = #Type;", con1)
cmd.Parameters.Add("#Type", DbType.String).Value = type
con1.Open
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

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

show database values in listbox when you open a form

I'm just new to vb.net.. Anyway, Is there a way when I open my form the items in my database will show up automatically?
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
list()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM Tbl", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(3) {}
Dim itm As ListViewItem
arr(0) = rdr("ID")
arr(1) = rdr("Name")
arr(2) = rdr("Brand")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
You can use below code
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Tbl")
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
End Using
End Using
End Using
Dim list As List(Of DataRow) = dt.AsEnumerable().ToList()
this code can convert direct data table to list.

How to select an excel data Table using a drop downlist value

I am working on an application that uses excel files as its data source. I would love the DataGridView to populate with the columns of a sheet when a worksheet name is selected from the drop down list.
Here is what I have tried doing:
Imports System.Data.OleDb
Public Class Form101
Public cn As New OleDbConnection
Public cm As New OleDbCommand
Public da As OleDbDataAdapter
Dim comb As String
Public dt As New DataTable
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comb1.SelectedIndexChanged
comb = Comb1.SelectedText
End Sub
Public Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Date"
.Columns(1).HeaderText = "Qty brought"
.Columns(2).HeaderText = "Qty sold"
.Columns(3).HeaderText = "Goods balance"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\toojah app\Stock card.xls; Extended Properties= Excel 8.0;"
cn.Open()
FillDataGridView("select * FROM ['" & comb & "'] ")
End Sub
End Class
Try something like this. The first function will collect all of the columns and records in your excel file and place it into a datatable. Then If you wanted to add additional columns to the datable you can do it in the Public Sub CreateDataGridView. This has been tested and works.
Friend Shared Function BuildDatatable () as datatable
Dim dt As New DataTable
Dim Conn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
dim MyFile as string = "C:\toojah app\Stock card.xls"
Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyFile + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
Conn.Open()
Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
cmd.TableMappings.Add("Table", "Net-informations.com")
cmd.Fill(dt)
Conn.Close()
Next
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
'This is used to pass the function datatable as a dt to then pass to the public sub as shown below.
Dim dt As DataTable = BuildDatatable
Public Sub CreateDataGridView(dt)
Dim newColumn As New Data.DataColumn("ComeColumnName", GetType(System.String))
newColumn.DefaultValue = "YourValues"
dt.Columns.Add(newColumn)
DataGridView1.DataSource = dt
End Sub

add autocomplete to textbox in vb.net

I've created a code for autocompletion, but dont know why it doesn't work.
Private Sub btnrefresh_Click(sender As Object, e As EventArgs) Handles btnrefresh.Click
txtledgersearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtledgersearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
getData(DataCollection)
txtledgersearch.AutoCompleteCustomSource = DataCollection
End Sub
Private Sub getData(ByVal dataCollection As AutoCompleteStringCollection)
On Error Resume Next
Dim adapter As New OleDbDataAdapter
con = New OleDbConnection(connectionString)
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
sqlstr = "SELECT LedgerTab.lname FROM LedgerTab;"
ds.Tables.Add(dt)
adapter.SelectCommand = New OleDbCommand(sqlstr, con)
For Each row As DataRow In ds.Tables(0).Rows
dataCollection.Add(row(0).ToString())
Next
End Sub
I'm not getting why my code is not working.
Check whether data is filled to dataCollection from DB.
try moving this scode snipet to load event
txtledgersearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtledgersearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
getData(DataCollection)
txtledgersearch.AutoCompleteCustomSource = DataCollection