ComboBox: dodawanie tekstu i wartości do elementu (bez wiążącego Źródła)

W C# WinApp, jak Mogę dodać tekst i wartość do elementów mojego ComboBox? Szukałem i zazwyczaj odpowiedzi używają "wiązania do źródła".. ale w moim przypadku nie mam gotowego wiążącego źródła w moim programie... Jak mogę zrobić coś takiego:

combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
Author: RustyTheBoyRobot, 2010-06-17

20 answers

Musisz utworzyć własny typ klasy i nadpisać metodę ToString (), aby zwrócić żądany tekst. Oto prosty przykład klasy, której możesz użyć:

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

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

Oto prosty przykład jego użycia:

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());
}
 372
Author: Adam Markowitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-17 16:04:53
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
        test.Add("1", "dfdfdf");
        test.Add("2", "dfdfdf");
        test.Add("3", "dfdfdf");
        comboBox1.DataSource = new BindingSource(test, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";

// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
 193
Author: fab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-31 17:32:02

Możesz użyć anonimowej klasy w ten sposób:

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "report A", Value = "reportA" });
comboBox.Items.Add(new { Text = "report B", Value = "reportB" });
comboBox.Items.Add(new { Text = "report C", Value = "reportC" });
comboBox.Items.Add(new { Text = "report D", Value = "reportD" });
comboBox.Items.Add(new { Text = "report E", Value = "reportE" });

UPDATE: chociaż powyższy kod będzie poprawnie wyświetlany w polu combo, nie będziesz mógł użyć SelectedValue lub SelectedText właściwości ComboBox. Aby móc z nich korzystać, bind combo box jak poniżej:

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

var items = new[] { 
    new { Text = "report A", Value = "reportA" }, 
    new { Text = "report B", Value = "reportB" }, 
    new { Text = "report C", Value = "reportC" },
    new { Text = "report D", Value = "reportD" },
    new { Text = "report E", Value = "reportE" }
};

comboBox.DataSource = items;
 123
Author: buhtla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-29 09:30:06

Powinieneś użyć dynamic object, aby rozwiązać element combobox w czasie wykonywania.

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "Text", Value = "Value" });

(comboBox.SelectedItem as dynamic).Value
 37
Author: Mert Cingoz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 18:01:11

Możesz użyć obiektu Dictionary zamiast tworzyć niestandardową klasę do dodawania tekstu i wartości w Combobox.

Dodaj klucze i wartości w obiekcie Dictionary:

Dictionary<string, string> comboSource = new Dictionary<string, string>();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");

Bind the source Dictionary object to Combobox:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Odzyskaj klucz i wartość:

string key = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Key;
string value = ((KeyValuePair<string,string>)comboBox1.SelectedItem).Value;

Pełne źródło: Combobox tekst nd wartość

 17
Author: cronynaval,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 13:35:03

To jest jeden ze sposobów, które właśnie przyszło mi do głowy:

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

I aby zmienić tekst lub wartość elementu, możesz to zrobić w następujący sposób:

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

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

Nie ma klasy o nazwie ListItem w Windows Forms. Istnieje tylko w ASP.NET , więc będziesz musiał napisać własną klasę przed jej użyciem, tak samo jak @Adam Markowitz zrobił to w jego odpowiedzi.

Sprawdź również te strony, mogą pomóc:

 15
Author: Amr Elgarhy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41

Nie wiem, czy to zadziała w sytuacji podanej w oryginalnym poście( nie ważne, że to dwa lata później), ale ten przykład działa dla mnie:

Hashtable htImageTypes = new Hashtable();
htImageTypes.Add("JPEG", "*.jpg");
htImageTypes.Add("GIF", "*.gif");
htImageTypes.Add("BMP", "*.bmp");

foreach (DictionaryEntry ImageType in htImageTypes)
{
    cmbImageType.Items.Add(ImageType);
}
cmbImageType.DisplayMember = "key";
cmbImageType.ValueMember = "value";

Aby odczytać wartość z powrotem, musisz oddać właściwość SelectedItem do obiektu DictionaryEntry, a następnie możesz ocenić właściwości klucza i wartości tego obiektu. Na przykład:

DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
MessageBox.Show(deImgType.Key + ": " + deImgType.Value);
 11
Author: ChuckG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-05 23:29:07
//set 
comboBox1.DisplayMember = "Value"; 
//to add 
comboBox1.Items.Add(new KeyValuePair("2", "This text is displayed")); 
//to access the 'tag' property 
string tag = ((KeyValuePair< string, string >)comboBox1.SelectedItem).Key; 
MessageBox.Show(tag);
 7
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-31 00:48:27

Jeśli ktoś nadal jest tym zainteresowany, oto prosta i elastyczna klasa dla elementu combobox z tekstem i wartością dowolnego typu (bardzo podobna do przykładu Adama Markowitza):

public class ComboBoxItem<T>
{
    public string Name;
    public T value = default(T);

    public ComboBoxItem(string Name, T value)
    {
        this.Name = Name;
        this.value = value;
    }

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

Używanie <T> jest lepsze niż deklarowanie value jako object, ponieważ z object będziesz musiał śledzić Typ, którego użyłeś dla każdego elementu i wrzucić go do kodu, aby poprawnie go używać.

[5]}używam go w moich projektach od dłuższego czasu. To jest naprawdę przydatne.
 5
Author: Matheus Rocha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-05 01:04:05

Spodobała mi się odpowiedź fab, ale nie chciałem używać słownika do mojej sytuacji, więc podstawiłem listę krotek.

// set up your data
public static List<Tuple<string, string>> List = new List<Tuple<string, string>>
{
  new Tuple<string, string>("Item1", "Item2")
}

// bind to the combo box
comboBox.DataSource = new BindingSource(List, null);
comboBox.ValueMember = "Item1";
comboBox.DisplayMember = "Item2";

//Get selected value
string value = ((Tuple<string, string>)queryList.SelectedItem).Item1;
 4
Author: Maggie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-17 18:04:28

Przykład użycia DataTable:

DataTable dtblDataSource = new DataTable();
dtblDataSource.Columns.Add("DisplayMember");
dtblDataSource.Columns.Add("ValueMember");
dtblDataSource.Columns.Add("AdditionalInfo");

dtblDataSource.Rows.Add("Item 1", 1, "something useful 1");
dtblDataSource.Rows.Add("Item 2", 2, "something useful 2");
dtblDataSource.Rows.Add("Item 3", 3, "something useful 3");

combo1.Items.Clear();
combo1.DataSource = dtblDataSource;
combo1.DisplayMember = "DisplayMember";
combo1.ValueMember = "ValueMember";

   //Get additional info
   foreach (DataRowView drv in combo1.Items)
   {
         string strAdditionalInfo = drv["AdditionalInfo"].ToString();
   }

   //Get additional info for selected item
    string strAdditionalInfo = (combo1.SelectedItem as DataRowView)["AdditionalInfo"].ToString();

   //Get selected value
   string strSelectedValue = combo1.SelectedValue.ToString();
 3
Author: Soenhay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-31 21:51:48

Możesz użyć tego kodu, aby wstawić niektóre elementy do pola kombi z tekstem i wartością.

C #

private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
    combox.Items.Insert(0, "Copenhagen");
    combox.Items.Insert(1, "Tokyo");
    combox.Items.Insert(2, "Japan");
    combox.Items.Insert(0, "India");   
}

XAML

<ComboBox x:Name="combox" SelectionChanged="ComboBox_SelectionChanged_1"/>
 3
Author: Muhammad Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-14 05:00:13

Możesz użyć typu generycznego:

public class ComboBoxItem<T>
{
    private string Text { get; set; }
    public T Value { get; set; }

    public override string ToString()
    {
        return Text;
    }

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

Przykład użycia prostego typu int:

private void Fill(ComboBox comboBox)
    {
        comboBox.Items.Clear();
        object[] list =
            {
                new ComboBoxItem<int>("Architekt", 1),
                new ComboBoxItem<int>("Bauträger", 2),
                new ComboBoxItem<int>("Fachbetrieb/Installateur", 3),
                new ComboBoxItem<int>("GC-Haus", 5),
                new ComboBoxItem<int>("Ingenieur-/Planungsbüro", 9),
                new ComboBoxItem<int>("Wowi", 17),
                new ComboBoxItem<int>("Endverbraucher", 19)
            };

        comboBox.Items.AddRange(list);
    }
 2
Author: Jan Staecker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-26 08:30:16

Kontynuując odpowiedź Adama Markowitza, oto ogólny sposób (względnie) po prostu ustawiania ItemSource wartości comboboxu na enums, jednocześnie pokazując użytkownikowi atrybut "Description". (Można by pomyśleć, że każdy chciałby to zrobić, aby był to . NET jeden liner, ale po prostu nie jest, i to jest najbardziej elegancki sposób, jaki znalazłem).

Najpierw utwórz tę prostą klasę do konwersji dowolnej wartości Enum na element ComboBox:

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

    public ComboEnumItem(Enum originalEnum)
    {
        this.Value = originalEnum;
        this.Text = this.ToString();
    }

    public string ToString()
    {
        FieldInfo field = Value.GetType().GetField(Value.ToString());
        DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
        return attribute == null ? Value.ToString() : attribute.Description;
    }
}

Po drugie w Twoim OnLoad event handler, musisz ustawić źródło listy ComboEnumItems na podstawie każdego Enum w twoim typie Enum. Można to osiągnąć za pomocą Linq. Następnie Ustaw DisplayMemberPath:

    void OnLoad(object sender, RoutedEventArgs e)
    {
        comboBoxUserReadable.ItemsSource = Enum.GetValues(typeof(EMyEnum))
                        .Cast<EMyEnum>()
                        .Select(v => new ComboEnumItem(v))
                        .ToList();

        comboBoxUserReadable.DisplayMemberPath = "Text";
        comboBoxUserReadable.SelectedValuePath= "Value";
    }

Teraz użytkownik wybierze z listy przyjazną użytkownikowi Descriptions, ale to, co wybierze, będzie wartością enum, której możesz użyć w kodzie. Aby uzyskać dostęp do wyboru użytkownika w kodzie, comboBoxUserReadable.SelectedItem będzie ComboEnumItem, a comboBoxUserReadable.SelectedValue będzie EMyEnum.

 2
Author: Bill Pascoe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-25 23:32:16

Class creat:

namespace WindowsFormsApplication1
{
    class select
    {
        public string Text { get; set; }
        public string Value { get; set; }
    }
}

Kody Form1:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            List<select> sl = new List<select>();
            sl.Add(new select() { Text = "", Value = "" });
            sl.Add(new select() { Text = "AAA", Value = "aa" });
            sl.Add(new select() { Text = "BBB", Value = "bb" });
            comboBox1.DataSource = sl;
            comboBox1.DisplayMember = "Text";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            select sl1 = comboBox1.SelectedItem as select;
            t1.Text = Convert.ToString(sl1.Value);

        }

    }
}
 1
Author: Limitless isa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-14 18:22:23

Miałem ten sam problem, co zrobiłem było dodanie nowego ComboBox z tylko wartość w tym samym indeksie następnie pierwszy, a następnie gdy zmieniam główne combo indeks w drugim zmienić w tym samym czasie, to biorę wartość drugiego combo i używać go.

Oto kod:

public Form1()
{
    eventos = cliente.GetEventsTypes(usuario);

    foreach (EventNo no in eventos)
    {
        cboEventos.Items.Add(no.eventno.ToString() + "--" +no.description.ToString());
        cboEventos2.Items.Add(no.eventno.ToString());
    }
}

private void lista_SelectedIndexChanged(object sender, EventArgs e)
{
    lista2.Items.Add(lista.SelectedItem.ToString());
}

private void cboEventos_SelectedIndexChanged(object sender, EventArgs e)
{
    cboEventos2.SelectedIndex = cboEventos.SelectedIndex;
}
 0
Author: Miguel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-29 00:18:58

Tak robi Visual Studio 2013:

Pojedynczy element:

comboBox1->Items->AddRange(gcnew cli::array< System::Object^  >(1) { L"Combo Item 1" });

Wiele Pozycji:

comboBox1->Items->AddRange(gcnew cli::array< System::Object^  >(3)
{
    L"Combo Item 1",
    L"Combo Item 2",
    L"Combo Item 3"
});

Nie ma potrzeby nadpisywania klas ani dołączania czegokolwiek innego. I tak połączenia comboBox1->SelectedItem i comboBox1->SelectedIndex nadal działają.

 0
Author: Enigma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-19 22:26:24

Jest to podobne do niektórych innych odpowiedzi, ale jest kompaktowe i pozwala uniknąć konwersji do słownika, jeśli masz już listę.

Podano ComboBox" combobox " w formularzu windows i klasie SomeClass z właściwością string type Name,

List<SomeClass> list = new List<SomeClass>();

combobox.DisplayMember = "Name";
combobox.DataSource = list;

Co oznacza, że SelectedItem jest obiektem SomeClass z list, a każdy element w combobox będzie wyświetlany przy użyciu jego nazwy.

 0
Author: Alex Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-06 19:22:21

Jest to bardzo proste rozwiązanie dla windows forms, jeśli potrzebna jest ostateczna wartość jako (string). Nazwy elementów zostaną wyświetlone na polu wyboru, a wybrana wartość może być łatwo porównana.

List<string> items = new List<string>();

// populate list with test strings
for (int i = 0; i < 100; i++)
            items.Add(i.ToString());

// set data source
testComboBox.DataSource = items;

I podczas obsługi zdarzenia pobieramy wartość (string) wybranej wartości

string test = testComboBox.SelectedValue.ToString();
 0
Author: Esteban Verbel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 15:48:04

Lepsze rozwiązanie tutaj;

Dictionary<int, string> userListDictionary = new Dictionary<int, string>();
        foreach (var user in users)
        {
            userListDictionary.Add(user.Id,user.Name);
        }

        cmbUser.DataSource = new BindingSource(userListDictionary, null);
        cmbUser.DisplayMember = "Value";
        cmbUser.ValueMember = "Key";

Dane Rekonwalescencyjne

MessageBox.Show(cmbUser.SelectedValue.ToString());
 0
Author: Orhan Bayram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-26 15:29:43