簡體   English   中英

C#在組合框中選擇一個值

[英]c# select a value in combobox

我在C#Windows窗體中的組合框充滿了數據庫中的數據...顯示成員是字符串,值成員是整數

現在,在顯示表單之前,我必須預先選擇它。 我努力了:

combobox.DisplayMember = string;
combobox.Text = string;
combobox.SelectedItem = string;
combobox.SelectedText = string;
combobox.SelectedValue = string;

任何可以給我一點幫助的人嗎? 會被應用很多:-)

編輯:ei。 也許是其他人的解決方案...請記住,由VS2010設計器創建的加載是在構造函數之后加載的。 如我所想,不在initializeComponents()中。

如果您的ComboBox是數據綁定的,並且已經正確設置了DisplayMember和ValueMember屬性,則只需將SelectedValue屬性設置為要選擇的項目的值即可。

例如,如果您的組合框中有以下對象:

ID  Description
--  -----------------
2   Lorem
4   Ipsum
6   Dolor
8   Sit

您可以將DisplayMember設置為“ Description”,將ValueMember設置為“ ID”。 然后,為了選擇項目“ Dolor”,只需將SelectedValue設置為6。

找到該Item然后將組合框的SelectedItem屬性設置為true。

編輯:

comboBox.SelectedItem = comboBox.Items.Cast<string>().First(o => o == "blala");

如果您的Items是字符串,請使用Cast<string>() ,快速組合框。Items將向您顯示對象。

如果我無法確切記住它是否是winforms,則應將selected Item的selected屬性設置為false,然后將另一個屬性設置為true。

檢查它,如果是這種情況,只需添加以下行:

combobox.SelectedIndex = -1;

使用ComboBox.SelectedIndex

例如:

myComboBox.SelectedIndex = [index of item to select];

請注意, ComboBox.Items是一個ObjectCollection ,它具有一個稱為IndexOf()的方法。 將其傳遞給您要選擇的對象的引用,然后應該返回正確的索引。

其他方式:

combobox.SelectedIndex = combobox.FindStringExact("myString")

暫無
暫無

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

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