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

后端 未结 4 1662
遇见更好的自我
遇见更好的自我 2021-01-21 18:38

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

相关标签:
4条回答
  • 2021-01-21 19:21

    Try this:

    cboColours.DataSource = dtColours 'For Windows Forms or

    cboColours.ItemsSource = dtColours 'For WPF

    0 讨论(0)
  • 2021-01-21 19:22
    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"
    
    0 讨论(0)
  • 2021-01-21 19:29

    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.

    0 讨论(0)
  • 2021-01-21 19:32

    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
    
    0 讨论(0)
提交回复
热议问题