选定的索引组合框winforms

时间:2016-05-10 17:36:04

标签: c# winforms data-binding combobox

好的,非常愚蠢的问题,但我还没有在互联网上找到答案。 我在表单上有多个comboboxes。每个binding的{​​{1}}位于form_load上。

加载表单时,在表单上选择第一个项目。这很明显,但我不想要这个。所以我在form_load中使用了以下代码:

combobox

这很有效。但文本框仍然给我第一项的数据?我的猜测是因为它在selectedIndexChanged中。但我不知道该使用什么。

如果我把private void InvoiceView_Load(object sender, EventArgs e) { // Bind list of customers to combobox CustomerComboBox.DataSource = invoicePresenter.getCustomers(); CustomerComboBox.DisplayMember = "CustomerName"; CustomerComboBox.ValueMember = "CustomerId"; // Bind list of products to combobox productCombobox.DataSource = invoicePresenter.getProducts(); productCombobox.DisplayMember = "ProductName"; productCombobox.ValueMember = "ProductId"; // Bind list of vat codes to combobox vatComboBox.DataSource = invoicePresenter.getTaxCodes(); vatComboBox.DisplayMember = "taxCodeShortDescr"; vatComboBox.ValueMember = "taxCodeId"; // Set comboboxes empty CustomerComboBox.SelectedItem = null; productCombobox.SelectedItem = null; vatComboBox.SelectedItem = null; } 我面临同样的问题。

代码:

combobox.selectedIndex = -1;

有人会想,因为我在文本框绑定中使用了selectitem,它也会为null。但事实并非如此。

2 个答案:

答案 0 :(得分:1)

有趣的是,您似乎已经遇到了其中一个WF数据绑定怪癖。问题是由于维护每个列表数据源的CurrencyManager类不允许将Position属性设置为-1(因此Currentnull)列表计数不为零。由于ComboBox正在使SelectedIndexCurrencyManager.Position同步,因此这有效地防止了具有未选择的项目。

作为解决方法,如果列表部分的数据绑定模式对您来说不是必不可少的,请替换

行。
CustomerComboBox.DataSource = invoicePresenter.getCustomers();

foreach (var customer in invoicePresenter.getCustomers())
    CustomerComboBox.Items.Add(customer);

对需要此类行为的其他组合框执行相同的操作。

答案 1 :(得分:0)

您可以删除组合框的SelectedIndex_Changed事件的处理程序,绑定数据,然后添加处理程序。像这样:

 private void InvoiceView_Load(object sender, EventArgs e)
 {
     this.CustomerComboBox.SelectedIndexChanged -= new EventHandler(CustomerComboBox_SelectedIndexChanged);
     this.productCombobox.SelectedIndexChanged -= new EventHandler(productCombobox_SelectedIndexChanged);
     this.vatComboBox.SelectedIndexChanged -= new EventHandler(vatComboBox_SelectedIndexChanged);

     // Bind list of customers to combobox
     CustomerComboBox.DataSource = invoicePresenter.getCustomers();
     CustomerComboBox.DisplayMember = "CustomerName";
     CustomerComboBox.ValueMember = "CustomerId";

     // Bind list of products to combobox
     productCombobox.DataSource = invoicePresenter.getProducts();
     productCombobox.DisplayMember = "ProductName";
     productCombobox.ValueMember = "ProductId";

     // Bind list of vat codes to combobox
     vatComboBox.DataSource = invoicePresenter.getTaxCodes();
     vatComboBox.DisplayMember = "taxCodeShortDescr";
     vatComboBox.ValueMember = "taxCodeId";


     this.CustomerComboBox.SelectedIndexChanged += new EventHandler(CustomerComboBox_SelectedIndexChanged);
     this.productCombobox.SelectedIndexChanged += new EventHandler(productCombobox_SelectedIndexChanged);
     this.vatComboBox.SelectedIndexChanged += new EventHandler(vatComboBox_SelectedIndexChanged);

 }