【问题标题】:WinForms Combox - Adding item to a databound list and then setting that to be the selecteditemWinForms Combox - 将项目添加到数据绑定列表,然后将其设置为选定项目
【发布时间】:2009-07-21 14:19:27
【问题描述】:

我有这个:

cmbConnections.DisplayMember = "Name";
cmbConnections.ValueMember = "Index";
cmbConnections.DataSource = DBConnectionSettings.ConnectionList;

一切都好!

现在将新项目添加到列表中:

DBConnectionSettings.Connection c = new DBConnectionSettings.Connection();
c.Name = reply;
c.Index = DBConnectionSettings.ConnectionList.Count + 1;
DBConnectionSettings.ConnectionList.Add(c);

我现在想在组合框中将这个新项目显示为选定项目。设置组合框的文本失败。

谢谢

【问题讨论】:

  • 你为什么要做 Count + 1,我认为 Count 至少是 1 基数,所以如果有的话,它会是 Count -1。

标签: c# .net winforms data-binding


【解决方案1】:

尝试在 DataSource 和 ComboBox 之间放置一个BindingSource。添加新项目后,调用 myBindingSource.ResetBindings(false);然后您将设置 myBindingSource 的 Position 属性或 ComboBox 的 SelectedValue 属性。

【讨论】:

    【解决方案2】:

    您已将组合框的 ValueMember 设置为“索引”,这意味着您可以通过将 ComboBox.SelectedValue 设置为项目的索引来选择组合框中的值。即:

    cmbConnections.SelectedValue = c.Index;
    

    【讨论】:

    • 抛出异常,不能将 SelectedValue 设置为 0
    猜你喜欢
    • 2010-10-07
    • 1970-01-01
    • 2011-06-09
    • 2021-08-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多