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

コンボボックスのアイテムをリストの最初のもの以外に設定するにはどうすればよいですか? 試したのは、comboBox.SelectedItem = someCustomer; です。...他にもたくさんありますが、これまでのところ運がありません...

4

3 に答える 3

14

やったほうがいい

comboBox.SelectedValue = "valueToSelect";

また

comboBox.SelectedIndex = n;

また

comboBox.Items[n].Selected = true;
于 2012-04-04T17:05:36.940 に答える
2

バインディング コードが完全ではありません。これを試して:

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 の [データ ソース] ウィンドウでデータ ソースを追加します。メニューView > Other Windows > Data Sourcesから開きます。タイプのオブジェクト データ ソースを追加しますCustomer。データ ソースには、顧客のプロパティが表示されます。プロパティを右クリックすると、関連付けられているデフォルト コントロールを変更できます。

これで、[データ ソース] ウィンドウからフォームにプロパティをドラッグするだけで済みます。最初のコントロールをドロップすると、 Visual Studio によって ABindingSourceとコンポーネントがフォームに自動的に追加されます。BindingNavigatorBindingNavigatorオプションであり、不要な場合は安全に削除できます。Visual Studio は、すべての接続も行います。プロパティウィンドウから微調整できます。これは、コンボ ボックスで必要になる場合があります。

コードで行うべきことは 1 つだけです。実際のデータ ソースをバインディング ソースに割り当てます。

customerBindingSource.DataSource = _customers;
于 2012-04-04T17:17:17.367 に答える