2011-10-23 26 views
0

我使用組合框,它看起來等同於選擇html標籤,但沒有組合框中的值? 例如:相當於選擇C#組件中的html標籤嗎?

HTML選擇:

<select name="foo"> 
<option value="baa">xxx</option> 
<option value="foo">yyy</option> 
</select> 

如果所選的數值xxx返回的值是baa

有可能與C#的一些組件做到這一點?

我希望這很清楚。提前致謝。

+1

訪問所選擇的項目也就是CombBoxItem的實例有可用的是相似的幾個控件,您可以使用普通的下拉框,這正好表現這樣 – kobe

回答

3

您可以使用常規的ComboBox控件,但稍作調整。在ComboBox中添加的每個項目都是object,並且在渲染時,它會調用ToString()方法。

我們可以創建一個自定義類添加爲ComboBox項:現在

public class ComboBoxItem 
{ 
    public ComboBoxItem(string value, string text) 
    { 
     Value = value; 
     Text = text; 
    } 

    public string Value { get; set; } 
    public string Text { get; set; } 

    public override string ToString() 
    { 
     return Text; 
    } 
} 

,您可以創建上述類的實例,並添加到收藏ComboxBox.Items

private void Form1_Load(object sender, EventArgs e) 
{ 
    comboBox1.Items.Add(new ComboBoxItem("1", "Green")); 
    comboBox1.Items.Add(new ComboBoxItem("2", "Blue")); 
    comboBox1.Items.Add(new ComboBoxItem("3", "Yellow")); 
} 

,您可以通過鑄造comboBox1.SelectedItemCombBoxItem

var comboBoxItem = (ComboBoxItem) comboBox1.SelectedItem; 
comboBoxItem.Text //Green/Blue/Yellow 
comboBoxItem.Value //1/2/3 
+0

完美!是我一直在尋找的。非常感謝。 –

+0

謝謝'面具':) –