使用SelectedValue时,绑定到组合框会得到不同的结果

时间:2014-06-11 21:24:13

标签: c# winforms binding combobox

我已经将这个简单的类绑定到了我的组合框:

  public class Company
  {
    public Guid CorporationId { set; get; }
    public Guid TokenId { set; get; }
    public string Name { set; get; }
  }

这是我的约束力:

private void FillCompaniesComboBox()
{
  _doneLoadingComboBox = false;
  comboBox_Companies.Items.Clear();

  if (CurrentSettings.AllCompanies.Count == 0)
  {
    return;
  }

  bindingSource1.DataSource = CurrentSettings.AllCompanies;
  comboBox_Companies.DataSource = bindingSource1.DataSource;
  comboBox_Companies.DisplayMember = "Name";
  comboBox_Companies.ValueMember = "CorporationId";
  comboBox_Companies.SelectedIndex = 1;
  _doneLoadingComboBox = true;
}

当我尝试获取所选项目的值时,我得到的结果不同。以下是我用来获取价值的代码:

private void comboBox_Companies_SelectedIndexChanged(object sender, EventArgs e)
{
  if (!_doneLoadingComboBox && comboBox_Companies.SelectedIndex == -1)
  {
    return;
  }

  var value = (Company)comboBox_Companies.SelectedValue;

  Console.WriteLine("Value: " + value.CorporationId);

}

以下是发生的事情:

这个有意为:

enter image description here

这是因为它引起了一个问题:

enter image description here

我没有正确检索数据吗?我需要它必须遵守的公司信息。

1 个答案:

答案 0 :(得分:0)

好的,这就是你需要做的......

假设您的CurrentSettings.AllCompaniesIList<Company>,您已经填充了数据,那么您的代码应该是这样的:

public class ComboBoxItem {
    // your class
    private Company Comp;
}

private readonly BindingSource _bsSelectedCompany = new BindingSource();
private readonly ComboBoxItem _comboBoxItem = new ComboBoxItem();

// your main form method
public MainForm() {

    // initialization code...
    InitializeComponent();

    // prevents errors in case your data binding objects are empty
    ResetComboBox(comboBox1);

    comboBox1.DataBindings.Add(new Binding(
        "SelectedItem",
        _bsSelectedCompany,
        "Comp",
        false,
        DataSourceUpdateMode.OnPropertyChanged
    ));

    comboBox1.DataSource = CurrentSettings.AllCompanies;
    comboBox1.DisplayMember = "Name";
}

// simple method for resetting a given combo box to a default state
private static void ResetComboBox(ComboBox comboBox) {
    comboBox.Items.Clear();
    comboBox.Items.Add("Select a method...");
    comboBox.SelectedItem = comboBox.Items[0];
}

通过这样做,您只需使用_comboBoxItem即可安全地获取有关所选项目的信息,而无需Invoke它(如果是单独访问它)线程)。