从 VB.Net 中的数据表填充组合框的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18609175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way of filling a combobox from a datatable in VB.Net
提问by Dean Martin
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?
下面代码中的数据表填充了7500-+条记录。这一切都从服务器快速加载。问题是循环遍历数据行以将它们添加到组合框需要一段时间。是否有其他方法可以设置组合框的数据源或加快此过程?
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()
回答by sloth
The fasted way would be to use the AddRange
method instead of using Add
, something like:
禁食的方法是使用AddRange
方法而不是使用Add
,例如:
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
.
我做了一个简单的检查,使用AddRange
速度比使用Add
.
Of course allocating an array and filling it with a For
loop would probably some milliseconds faster than using Linq.
当然,分配一个数组并用For
循环填充它可能比使用 Linq 快几毫秒。
回答by user3869653
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).
您还可以将 ComboBox DataSource 属性绑定到 DataTable。这具有绑定其他列数据(例如您可能不希望用户看到的键值)的额外优势。
You should be able to return a DataTable object from your SQLAdapter.
您应该能够从 SQLAdapter 返回一个 DataTable 对象。
cboColours.DataSource = dtColours
cboColours.DisplayMember = dtColours.Columns("Colour").ToString
cboColours.ValueMember = dtColours.Columns("Colour_id").ToString
回答by MANthan N Patel
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"
回答by mhneri
Try this:
尝试这个:
cboColours.DataSource = dtColours 'For Windows Forms
or
cboColours.DataSource = dtColours 'For Windows Forms
或者
cboColours.ItemsSource = dtColours 'For WPF
cboColours.ItemsSource = dtColours 'For WPF