簡體   English   中英

C#-從組合框中檢索選定的值

[英]C# - retrieve the selected value from a combobox

我有一個具有ValueMember = IDDisplayMember = Name的comboBox。 我需要與該名稱關聯的值,所以我需要執行以下操作:

if (cboTypeOfMaterial.SelectedIndex != -1)
            {
                string temp = cboTypeOfMaterial.SelectedValue.ToString();
                //More code here...
            }

返回ID值作為字符串。 例如-“ 7”。

如果我嘗試:

if (cboTypeOfMaterial.SelectedIndex != -1)
                {
                    string temp = cboTypeOfMaterial.DisplayMember.ToString();
                    //More code here...
                }

我得到的字符串Name是關鍵。

我需要獲取所選元素的Name的值

嘗試通過SelectedItem訪問元素,這將為您提供與該條目關聯的整個對象,然后您可以使用案例ID來訪問所需的屬性。

SelectedValue將返回ValueMember定義的屬性的ValueMemberSelectedItem將返回SelectedItem的整個對象,如果您想獲得除SelectedValue之外的其他值,則必須將其轉換為ComboBox的對象,然后才能訪問您的Name屬性。

string temp = (cboTypeOfMaterial.SelectedItem as YourObjectType).Name;

您可以做的是為comboBox中的條目創建一個自定義類。 看起來可能像:

public class ComboBoxItem
{
    public string Display { get; set; }
    public int Id { get; set; }
    public override string ToString()
    {
        return this.Display;
    }
}

然后,您可以通過以下代碼獲取所選的ComboBoxItem:

ComboBoxItem cbi = (ComboBoxItem)cboTypeOfMaterial.SelectedValue;
if(cbi != null)
   // Access the Property you need

我知道這是一個老問題,但我很驚訝沒有人提到:

ComboBox1.GetItemText(ComboBox1.SelectedItem)

它返回所選項目的文本表示形式(即DisplayMember ),在涉及數據綁定ComboBox或與此相關的任何ListControl情況下很有用。

string temp = cboTypeOfMaterial.ValueMember.ToString();

我認為您也可以使用Text屬性,但這不是一個很好的解決方案。 更好的解決方案是建議使用@dutzu。

string temp = cboTypeOfMaterial.Text;

暫無
暫無

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

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