Click here to Skip to main content
15,906,569 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all
How can i fill items in my combobox and display selected item values in label !!!!
For ex:
Display text ( year1,year2)
Values ( 2015,2016)

When i choose year1 from combobox the label will display 2015
And so on
Please help me
Thanks alot
Posted

Please follow below steps achieve the same:

Step1: Create a custom class for ComboBox Listitem
C#
public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }
}

Step2: Create object of custom class(ComboboxItem) and add those objects to ComboBox
C#
ComboboxItem item = new ComboboxItem();
item.Text = "year1";
item.Value = "2015";
comboBox1.Items.Add(item);

item = new ComboboxItem();
item.Text = "year2";
item.Value = "2016";
comboBox1.Items.Add(item);

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

Step3: On button click get the selected value of ComboBox
C#
private void button1_Click(object sender, EventArgs e)
{
   label1.Text = (comboBox1.SelectedItem as ComboboxItem).Value.ToString();
}
 
Share this answer
 
Comments
sam9787 7-Oct-16 15:59pm    
but how can i get all checked values in my checkboxlist ?
something like that but it doesnt work
it is always get 2016
for (int i = 0; i < checkedListTrainingRoom.Items.Count; i++)
if (checkedListTrainingRoom.GetItemChecked(i))
{
label1.Text = (checkedListTrainingRoom.SelectedItem as ComboboxItem).Value.ToString();

}
A convenient way to do this is to bind the ComboBox to a generic Dictionary as a DataSource:
C#
//required

using System;
using System.Collections.Generic;
using System.Windows.Forms;

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<string, string> ComboEntries = new Dictionary<string, string>
    {
       {"year1, year2", "2015, 2016"},
       {"year3, year4", "2017, 2018"}
    };

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

private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
    label1.Text = string.Format("Value selected: {0}", comboBox1.SelectedValue);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900