Fastest way of filling a combobox from a datatable in VB.Net - vb.net

The data table in the following code is filled with 7500-+ records. This all loads quickly from the server. The problem is that it takes a while to loop through the data rows to add them to the combo box. Is there any alternative way of setting the data source of the combo box or a way of speeding this process up?
Dim dtColours As New DataTable
Dim daColours As New SqlDataAdapter
Dim i As Integer
ConnectToSQL()
daColours = New SqlDataAdapter("SELECT DISTINCT Rtrim(UPPER(Colour)) As Colour FROM invStockColour WHERE InUse = 1 ORDER BY Colour", dbSQL)
daColours.Fill(dtColours)
For i = 0 To dtColours.Rows.Count - 1
cboColours.Items.Add(dtColours.Rows(i).Item(0).ToString)
Next
dbSQL.Close()

The fasted way would be to use the AddRange method instead of using Add, something like:
Dim items = dtColours.AsEnumerable().Select(Function(d) DirectCast(d(0).ToString(), Object)).ToArray()
cboColours.Items.AddRange(items)
I did a simple check and using AddRange is ~3x faster than using Add.
Of course allocating an array and filling it with a For loop would probably some milliseconds faster than using Linq.

Dim daColours As New SqlDataAdapter("SELECT DISTINCT Rtrim(UPPER(Colour)) As Colour FROM invStockColour WHERE InUse = 1 ORDER BY Colour", dbSQL)
Dim dtColours As New DataTable
daColours.Fill(dtColours)
cboColours.DataSource=dtColours
cboColours.DisplayMember="Colour"

You could also bind your ComboBox DataSource property to the DataTable. This has the added advantage of binding other column data (such as key values you might not want the user to see).
You should be able to return a DataTable object from your SQLAdapter.
cboColours.DataSource = dtColours
cboColours.DisplayMember = dtColours.Columns("Colour").ToString
cboColours.ValueMember = dtColours.Columns("Colour_id").ToString

Try this:
cboColours.DataSource = dtColours 'For Windows Forms or
cboColours.ItemsSource = dtColours 'For WPF

Related

Filter DataGridView across all columns

Sorry for my bad English. I am an old German man, I want to filter a DGV across all columns. In the Moment I use following filter:
Dim Such_Spalte = Me.DtS_DGV.DTT_1.article_1Column.ColumnName
But I have 10 Columns (article_1 to Article_10)
If as an example Sugar is in column 1,3,5 I want to see all records where sugar occurs.
I hope this is understandable
You seem to be using strongly typed datasets and as such I would expect that your datagridview is bound through a BindingSource (the windows forms designer sets it up this way, and my presumption is that you used te designer to do your binding)
If your datagridview is indeed bound through a bindingsource:
Dim bs = DirectCast(datagridviewX.DataSource, BindingSource)
Dim sb = New StringBuilder() 'it will hold the filter string
For Each col in DtS_DGV.DTT_1.Columns
sb.AppendFormat("[{0}] = '{1}' OR ", col.ColumnName, "Sugar")
Next col
sb.Length -= 3 'remove the trailing OR
bs.Filter = sb.ToString()
If your datagridview is bound direvtly to the table, it will have attached to the table's DefaultView property, a DataView, which also has a Filter that works in the same way. If this is the case, do the same thing with the loop to build the filter string, and then:
DtS_DGV.DTT_1.DefaultView.Filter = sb.ToString()

when I choose a value from the first compbox is the value of the remaining compbox is changed

I have 3 compobboxes I have created an import code from a SQL table
The problem when I choose a value from the first compbox
the values of other compbox is changed to be like my choice
I made a separate code for each compbox
But I find it impractical because my project has 90 compoboxes
It needs time to run
Is there a more practical solution?
this is my code...
Dim com As New SqlCommand("select Distinct Name1 from TB_dr", Con)
Dim RD As SqlDataReader = com.ExecuteReader
Dim DT As DataTable = New DataTable
DT.Load(RD)
ComboBox1.DisplayMember = "Name1"
ComboBox1.DataSource = DT
ComboBox2.DisplayMember = "Name1"
ComboBox2.DataSource = DT
ComboBox3.DisplayMember = "Name1"
ComboBox3.DataSource = DT
Only populate a combobox on its dropdown event.
That will make your app faster cause your client may not use them all and if he uses one combobox he would populate a small amount of data only.
And no data is populated on load.
As i look at what you are trying to do which is same data for all comboboxes, you can simply put all your comboboxes in a group, and go through your group to populate them all at once.
like for each cb in that group, cb.datasource = dt.
call the datatable once

How do I query a local datatable and return information to a datatable in VB.net

I am trying to pass a query and existing datatable into a function. The function will query the passed datatable using the passed query and return the result.
Unfortunately, I am unable to return any data. I have posted my code below. Can anyone help me fix it? I don't know what I am doing wrong.
Public Function ExecQueryTest(Query As String, DT As DataTable) As DataTable
Dim Result() As DataRow
'initialize the table to have the same number of columns of the table that is passed into the function
Dim LocalTable As DataTable = DT
'initialize counting variables
Dim x, y As Integer
'use the select command to run a query and store the results in an array
Result = DT.Select(Query)
'remove all items from the localtable after initial formatting
For x = 0 To LocalTable.Rows.Count - 1
LocalTable.Rows.RemoveAt(0)
Next
'for loop to iterate for the amount of rows stored in result
For x = 0 To Result.GetUpperBound(0)
'add each array row into the table
LocalTable.Rows.Add(Result(x))
Next
ExecQueryTest = LocalTable
End Function
If there is a better way to accomplish my goal, I don't mind starting from scratch. I just want to be able to handle dynamic tables, queries, and be able to return the information in a datatable format.
The problem is here:
Dim LocalTable As DataTable = DT
That code does not do what you think it does. DataTable is a reference type, which means assigning DT to the LocalTable variable only assigns a reference to the same object. No new table is created, and nothing is copied. Therefore, this later code also clears out the original table:
'remove all items from the localtable after initial formatting
For x = 0 To LocalTable.Rows.Count - 1
LocalTable.Rows.RemoveAt(0)
Next
Try this instead:
Public Function ExecQueryTest(Query As String, DT As DataTable) As DataTable
ExecQueryTest = New DataTable() 'create new DataTable object to hold results
For Each row As DataRow In DT.Select(Query)
ExecQueryTest.LoadDataRow(row.ItemArray, True)
Next
End Function
Though you may also need to clone each DataRow record.
You can clear a table with just
LocalTable.Clear()
instead of using that cycle, Also the results of your select can be directly converted to datatable using
LocalTable = Result.CopyToDataTable

Clear all the value of a datagridview column once in vb.net

i have user below code to clear the cell value of a datagridview column.
For Each item As DataGridViewRow In dgvGeometricImport.Rows
item.Cells("Status1").Value = String.Empty
Next
Do we have any short cut to clear all value without iterating the rows?
can we use linq to achieve this?
thanks in advance
With or without a DataSource set, you can *remove and re-add the column.
VB Example with DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").DisplayIndex
Dim table As DataTable = DirectCast(Me.dataGridView1.DataSource, DataTable)
Dim column As DataColumn = table.Columns("Status1")
table.Columns.Remove(column)
table.Columns.Add(column)
Me.dataGridView1.Columns("Status1").DisplayIndex = index
VB Example without DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").Index
Dim column As DataGridViewColumn = Me.dataGridView1.Columns("Status1")
Me.dataGridView1.Columns.Remove(column)
Me.dataGridView1.Columns.Insert(index, column)
*Disclaimer: This will work, but if I'm being honest I can't say for certain that there's no iteration occurring at some lower level. After all, when you re-add the column it becomes a part of each row entry and therefore could have been iterated through under-the-hood.
One approach would be to use jQuery selectors. It would of course still iterate through the rows, but it would be done client side and behind the scene.
$('#' + gridViewCtlId + ' td:nth-child(' + INDEX_COLUMN_TO_CLEAR + ')').html('');
use this :
dataGridView.Rows.Cast(Of DataGridViewRow).ToList.ForEach(Sub(r) r.Cells("ColumnName").Value = String.Empty)
but it's the same thing, linq will do the iteration

Get the BindingSource position based on DataTable row

I have a datatable that contains the rows of a database table. This table has a primary key formed by 2 columns.
The components are assigned this way: datatable -> bindingsource -> datagridview. What I want is to search a specific row (based on the primary key) to select it on the grid. I cant use the bindingsource.Find method because you only can use one column.
I have access to the datatable, so I do manually search on the datatable, but how can I get bindingsource row position based on the datatable row? Or there is another way to solve this?
Im using Visual Studio 2005, VB.NET.
I am attempting to add an answer for this 2-year old question. One way to solve this is by appending this code after the UpdateAll method(of SaveItem_Click):
Me.YourDataSet.Tables("YourTable").Rows(YourBindingSource.Position).Item("YourColumn") = "YourNewValue"
Then call another UpdateAll method.
Well, I end up iterating using bindingsource.List and bindingsource.Item. I didnt know but these properties contains the data of the datatable applying the filter and sorting.
Dim value1 As String = "Juan"
Dim value2 As String = "Perez"
For i As Integer = 0 To bsData.Count - 1
Dim row As DataRowView = bsData.Item(i)
If row("Column1") = value1 AndAlso row("Column2") = value2 Then
bsData.Position = i
Return
End If
Next