3

我有 2 个组合框,每个都绑定到同一个 DataTable,如下所示:

    channelTypeCB.DataSource = SynergyData.ds.Tables["ChannelTypes"];
    channelTypeCB.DisplayMember = "channelType";
    channelTypeCB.ValueMember = "channelTypeID";
    channelTypeCB.BindingContext = new BindingContext();

    newSKChanTypeCB.DataSource = SynergyData.ds.Tables["ChannelTypes"];
    newSKChanTypeCB.DisplayMember = "channelType";
    newSKChanTypeCB.ValueMember = "channelTypeID";
    newSKChanTypeCB.BindingContext = new BindingContext();

当我单击按钮将记录插入数据库时​​,我使用 channelType.SelectedValue... 返回错误的值。我感觉它与使用 ComboBox 排序(我在设计视图中的控件属性中设置)有关。有没有人遇到过这个问题?

这是使用 C# 为 winforms 应用程序编写的

编辑:

例如,我的 Datatable 存储如下值:

channelType    channelTypeID
Web             2
Mailer          3
Catalog         4

这是在组合框中排序的,当我选择第一个项目(排序时将是“目录”)时,SelectedValue 返回 2,当我选择第二个项目时,它返回 3....返回 4

4

5 回答 5

5

MSDN ComboBox.Sorted

大概和这个有关

尝试在数据绑定控件上设置 Sorted 属性会引发 ArgumentException。您必须使用基础数据模型对数据进行排序。

(虽然没有收到任何错误)

因此,我没有使用 ComboBox.sort,而是对 DataTable 的 DefaultView 进行排序:

SynergyData.ds.Tables["ChannelTypes"].DefaultView.Sort = "channelType";

不相信这是最好的方法,但它有效,现在 selectedValue 返回正确的东西

于 2009-10-03T03:16:29.130 回答
1

当您需要引用 newSKChanTypeCB.SelectedValue 时,您可能会在代码中引用 channelTypeCB.SelectedValue (这完全是基于您的控件名称的猜测)。

于 2009-10-03T02:44:52.797 回答
1

我会以不同的方式执行此操作:我将创建 2 个单独BindingSource的 ,每个都基于您的DataSet,然后将每个控件绑定DataSourceBindingSource刚刚创建的相应控件。

于 2009-10-03T02:55:28.660 回答
0

这是 .net 中的一个已知问题

请对此进行投票以在.net 5中修复它: http ://connect.microsoft.com/VisualStudio/feedback/details/542353/combobox-selectedvalue-returns-incorrect-data-when-sorted-is-true

于 2011-09-07T12:59:26.913 回答
0

问题是 ComboBox 的 Sorted 属性,因为您的数据来自 DataTable。

使用 Sorted 属性时,ComboBox 仅组织 DisplayMember 并忽略其他数据,因为它不能直接修改 DataTable。例子:

来自 DataTable 的数据作为 DataSource 没有排序

channelType   channelTypeID  ComboBoxDisplayMember    ComboboxValueMember
Web            2              Web                       2
Mailer         3              Mailer                    3
Catalog        4              Catalog                   4

现在使用排序属性

channelType   channelTypeID  ComboBoxDisplayMemberSorted   ComboboxValueMember
Web            2              Catalog                       2
Mailer         3              Mailer                        3
Catalog        4              Web                           4

这个问题可以在查询末尾添加的数据库中解决:“ORDER BY FieldName” http://technet.microsoft.com/en-us/library/ms188385.aspx

于 2013-12-10T15:45:57.243 回答