views:

61

answers:

2

In C# WinApp, How Can I add both Text and Value to the items of my comboBox? I did a search and usually the answers are using "Binding to a source".. but in my case I do not have that source ready in my program... how can I do something like this:

combo1.Item[1] = "DisplayText"; combo1.Item[1].Value = "useful Value"

+1  A: 

this is one of the ways come to head now:

combo1.Items.Add(new ListItem("Text", "Value"))

And to change text of or value of an item you can do it like that:

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

UPDATE: There is nothing called ListItem in winforms, it just exist in ASP.Net, so you will need to write down this class before using it, the same as @Adam Markowitz did in his answer.

Also check these pages, it may help:
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/c7a82a6a-763e-424b-84e0-496caa9cfb4d/

http://msdn.microsoft.com/en-us/library/19fc31ss.aspx

Amr ElGarhy
Unless I am mistaken, ListItem is only available in ASP.NET
Adam Markowitz
yes :( unfortunately it is only in ASP.net ... so what can I do now?
BDotA
Yes, just notice this and i updated my answer.
Amr ElGarhy
+3  A: 

You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

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

The following is a simple example of its usage:

private void Test()
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);

    comboBox1.SelectedIndex = 0;

    MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
Adam Markowitz
do we realy need this new class ComboboxItem? i think there is one already exist called ListItem.
Amr ElGarhy
I believe that may only be available in ASP.NET and not WinForms.
Adam Markowitz
Yes seams you are right, it just exist in ASP.Net
Amr ElGarhy
yes :( unfortunately it is only in ASP.net ... so what can I do now?
BDotA
No. The item is a separate type that is only used for storing the data of the items (text, value, references to other objects, etc). It is not a descendant of a ComboBox and it would be extremely rare that it would be.
Adam Markowitz
Thanks Adam, Works great.
BDotA