将数据表分配给组合框,然后进行更改 [英] Assigning a DataTable to a ComboBox and then making changes

查看:82
本文介绍了将数据表分配给组合框,然后进行更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

'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

似乎我不-建立链接,我得到相同的项目。但是,由于cbo已经链接到dt变量了,所以我不需要每次都重新链接它。这是怎么工作的,还是我在这里做错了?

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.DataSource时= dt ,然后重新创建 dt cbo.DataSource 会一直指向旧表。这是在这里工作的纯指针逻辑,相同的原理适用于所有.NET代码。这并不意味着您正在重复使用同一变量。相反,您可以创建 dt2 并使用它,行为将是相同的。因此,是的,如果您重新创建 DataTable ,则需要再次重新分配 DataSource 。但是,如果您更改原始的 dt ,即添加行,则会显示这些行,因此您无需重新分配 DataSource 。下面是一个代码示例,以说明该方法:

When you assign cbo.DataSource = dt, and you then recreate dt, cbo.DataSource will 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 dt2 and used that, behavior would be the same. So yes, if you recreate the DataTable, you need to reassign DataSource again. 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:

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

这篇关于将数据表分配给组合框,然后进行更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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