从 VB.Net 中的数据表填充组合框的最快方法 [英] Fastest way of filling a combobox from a datatable in VB.Net

查看:30
本文介绍了从 VB.Net 中的数据表填充组合框的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中的数据表填充了7500-+条记录.这一切都从服务器快速加载.问题是循环遍历数据行以将它们添加到组合框需要一段时间.是否有其他方法可以设置组合框的数据源或加快此过程?

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()

推荐答案

禁食的方法是使用 AddRange 方法而不是使用 Add 方法,例如:

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)

我做了一个简单的检查,使用 AddRange 比使用 Add 快约 3 倍.

I did a simple check and using AddRange is ~3x faster than using Add.

当然,分配一个数组并用 For 循环填充它可能比使用 Linq 快几毫秒.

Of course allocating an array and filling it with a For loop would probably some milliseconds faster than using Linq.

这篇关于从 VB.Net 中的数据表填充组合框的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆