vb.net 将 DataTable 分配给 ComboBox 然后进行更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13300194/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:24:43  来源:igfitidea点击:

Assigning a DataTable to a ComboBox and then making changes

vb.netcomboboxdatatabledatasource

提问by sinDizzy

VB2010 I have created a DataTable manually so it does not come from a database. I have assigned it to a combobox and it displays my column of data. If I change the DataTable do I have to re-establish the link?

VB2010 我手动创建了一个 DataTable,所以它不是来自数据库。我已将它分配给一个组合框,它显示了我的数据列。如果我更改了 DataTable 是否必须重新建立链接?

'assign first table
dt = GetFirstTable()
cbo.DataSource = dt
cbo.DisplayMember = "Time"
cbo.ValueMember = "Time"

'print out items in combobox

'assign second table
dt = GetSecondTable()
'cbo.DataSource = dt 'do i have to re-connect here?

'print out items in combobox

It seems if I do not re-establish the link I get the same items. I though since the cbo was already linked to the dt variable i didn't need to re-link it each time. Is that how that works or am I doing something wrong here?

看来如果我不重新建立链接,我会得到相同的项目。我虽然因为 cbo 已经链接到 dt 变量,所以我不需要每次都重新链接它。这是如何工作的还是我在这里做错了什么?

回答by Neolisk

When you assign cbo.DataSource = dt, and you then recreate dt, cbo.DataSourcewill keep pointing to the old table. This is pure pointer logic working here, same principle applies to all .NET code. It does not mean anything that you are re-using the same variable. You could have instead created dt2and used that, behavior would be the same. So yes, if you recreate the DataTable, you need to reassign DataSourceagain. However, if you change the original dt, i.e. add rows, those will appear, so you will not need to reassign DataSource. Here is a code sample, to illustrate the approach:

当您分配cbo.DataSource = dt,然后重新创建时dtcbo.DataSource将继续指向旧表。这是在这里工作的纯指针逻辑,同样的原则适用于所有 .NET 代码。这并不意味着您重新使用相同的变量。您可以改为创建dt2和使用它,行为将是相同的。所以是的,如果您重新创建DataTable,则需要DataSource再次重新分配。但是,如果您更改原始dt,即添加行,则会出现那些,因此您无需重新分配DataSource。这是一个代码示例,用于说明该方法:

Dim _dt As DataTable

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  _dt = New DataTable
  With _dt.Columns
    .Add("key")
    .Add("value")
  End With
  With ComboBox1
    .DisplayMember = "value"
    .ValueMember = "key"
    .DataSource = _dt
  End With
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
  _dt.Rows.Add({"item_key", "item_value"})
End Sub