在Windows窗体(VB)中更改数据源时,为什么这些组合框不能正确更新?

时间:2009-09-27 10:23:48

标签: vb.net winforms combobox datasource

在Windows窗体项目中,我有几个组合框。第一个组合框包含一个对象列表。这些对象有几个列表,用作连续组合框的数据源,具体取决于第一个选择的项目。

选择第一项时,其他组合框会正确更新。当第二次(或任何连续时间)更改此项目时,其他组合框不会正确更新。在调试时,它显示其他组合框正确分配了数据源,并且项目的“计数”正确。但这些物品实际上并没有显示出来。可能是什么原因?

Private Sub cmbPackage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPackage.SelectedIndexChanged
    // The Package controls what other options are available. 
    If (TypeOf (cmbPackage.SelectedItem) Is Package) Then
        // Set current package as a member object to see if it was a scoping issue
        _currentPackage = CType(cmbPackage.SelectedItem, Package)
        ClearOptionDropdowns()
        cmbReward.DataSource = _currentPackage.Rewards
        cmbPayment.DataSource = _currentPackage.PaymentTypes
        cmbCommMethod.DataSource = _currentPackage.CommunicationMethods
        cmbBillMethod.DataSource = _currentPackage.BillMethods
        cmbNotification.DataSource = _currentPackage.BillNotifications

        cmbReward.Refresh()
        cmbPayment.Refresh()
        cmbCommMethod.Refresh()
        cmbBillMethod.Refresh()
        cmbNotification.Refresh()
        ...
        ...
End Sub

Private Sub ClearOptionDropdowns()
    cmbReward.DataSource = Nothing
    cmbPayment.DataSource = Nothing
    cmbCommMethod.DataSource = Nothing
    cmbBillMethod.DataSource = Nothing
    cmbNotification.DataSource = Nothing
    ' Also had x.items.clear(), but removed to see if that was affecting it
End Sub

1 个答案:

答案 0 :(得分:1)

使用Reflector查看设置数据源时会发生什么,调用以下方法:

base.DataSource = value;

然后这样做:

if (this.dataSource != value)
    {
        try
        {
            this.SetDataConnection(value, this.displayMember, false);
        }

SetDataConnection:

private void SetDataConnection(object newDataSource, BindingMemberInfo newDisplayMember, bool force)
{
    bool flag = this.dataSource != newDataSource;
    bool flag2 = !this.displayMember.Equals(newDisplayMember);
    if (!this.inSetDataConnection)
    {
        try
        {
            if ((force || flag) || flag2)
            {
               // Update Accordingly

如果我使用Guid.NewGuid.ToString手动设置DisplayMember,则数据源会正确更新。似乎数据源比较确定它们最确定不相同时它们是相同的。即使我调用.DataSource = new List(Of ...)(list)也不会正确更新。

Object.Equals方法执行此操作:

 InternalEquals(object objA, object objB);

我假设做了一个指针比较?编译器可能正在进行哪些优化以缓存一个List对象,然后在运行时使用所需的值填充该列表?我确定在创建对象时每个List都是一个新的List(Of type)。