簡體   English   中英

在綁定到數據源的 combobox 上設置 SelectedItem

[英]Set SelectedItem on a combobox bound to datasource

List<Customer> _customers = getCustomers().ToList();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;
comboBox.DataSource = bsCustomers.DataSource;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";

現在如何將組合框的 Item 設置為列表中第一個以外的其他內容? 試過 comboBox.SelectedItem = someCustomer; ......還有很多其他的東西,但到目前為止還沒有運氣......

你應該做

comboBox.SelectedValue = "valueToSelect";

要么

comboBox.SelectedIndex = n;

要么

comboBox.Items[n].Selected = true;

您的綁定代碼不完整。 試試這個:

BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;

comboBox.DataBindings.Add(
    new System.Windows.Forms.Binding("SelectedValue", bsCustomers, "id", true));
comboBox.DataSource = bsCustomers;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";

在大多數情況下,您可以在設計器中完成此任務,而不是在代碼中完成。

首先在 Visual Studio 的“數據源”window 中添加一個數據源。 從菜單View > Other Windows > Data Sources打開它。 添加Customer類型的Object數據源。 在數據源中,您將看到客戶的屬性。 通過右鍵單擊屬性,您可以更改與其關聯的默認控件。

現在您只需將屬性從數據源 window 拖到您的表單中。 當您放下第一個控件時,Visual Studio 會自動將BindingSourceBindingNavigator組件添加到您的窗體。 BindingNavigator是可選的,如果不需要,您可以安全地刪除它。 Visual Studio 也完成所有的連接工作。 您可以通過屬性 window 對其進行調整。有時組合框需要這樣做。

您的代碼中只剩下一件事要做:將實際數據源分配給綁定源:

customerBindingSource.DataSource = _customers;

這對我有用

bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM