首页 文章

ComboBox:向项添加文本和值(无绑定源)

提问于
浏览
167

在C#WinApp中,如何将Text和Value添加到我的ComboBox的项目中?我做了一个搜索,通常答案是使用“绑定到源”..但在我的情况下,我的程序中没有准备好绑定源...我怎么能这样做:

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

20 回答

  • 1

    你可以使用这段代码combox add item with text and its value

    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");
                
               
            }
    

    使用文本和值将一些项插入到combox中 . 在这里xaml code for combox

  • 13

    您必须创建自己的类类型并覆盖ToString()方法以返回所需的文本 . 以下是您可以使用的类的简单示例:

    public class ComboboxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }
    
        public override string ToString()
        {
            return Text;
        }
    }
    

    以下是其用法的简单示例:

    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());
    }
    
  • 319
    // 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;
    
  • 0

    你可以像这样使用匿名类:

    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: 虽然上面的代码会在组合框中正确显示,但您将无法使用 ComboBoxSelectedValueSelectedText 属性 . 为了能够使用它们,绑定组合框如下:

    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;
    
  • 3

    您应该使用 dynamic 对象在运行时解析组合框项目 .

    comboBox.DisplayMember = "Text";
    comboBox.ValueMember = "Value";
    
    comboBox.Items.Add(new { Text = "Text", Value = "Value" });
    
    (comboBox.SelectedItem as dynamic).Value
    
  • 11

    这是我想到的方式之一:

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

    要更改项目的文本或值,您可以这样做:

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

    Windows Forms中没有名为ListItem的类 . 它只存在于ASP.NET中,所以在使用之前你需要编写自己的类,就像@Adam Markowitz在his answer中所做的那样 .

    还要检查这些页面,它们可能有所帮助:

  • 0

    不知道这是否适用于原帖中给出的情况(更不用说这是两年后的事实),但这个例子对我有用:

    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";
    

    要重新读取您的值,您必须将SelectedItem属性强制转换为DictionaryEntry对象,然后您可以评估它的Key和Value属性 . 例如:

    DictionaryEntry deImgType = (DictionaryEntry)cmbImageType.SelectedItem;
    MessageBox.Show(deImgType.Key + ": " + deImgType.Value);
    
  • 0

    您可以使用 Dictionary Object而不是创建自定义类来在 Combobox 中添加文本和值 .

    Dictionary 对象中添加键和值:

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

    将源Dictionary对象绑定到 Combobox

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

    检索键和值:

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

    完整来源:Combobox Text nd Value

  • 174
    //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);
    
  • 2

    我喜欢fab的答案,但不想为我的情况使用字典,所以我替换了一个元组列表 .

    // 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;
    
  • 1

    使用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();
    
  • 102

    如果有人仍然对此感兴趣,这里有一个简单灵活的类,用于具有文本和任何类型值的组合框项目(非常类似于Adam Markowitz的示例):

    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;
        }
    }
    

    使用 <T> 比将 value 声明为 object 更好,因为使用 object ,您必须跟踪每个项目使用的类型,并将其强制转换为代码以正确使用它 .

    我已经在我的项目上使用它已经有一段时间了 . 这真的很方便 .

  • 0

    您可以使用通用类型:

    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;
        }
    }
    

    使用简单int-Type的示例:

    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);
        }
    
  • 0

    继Adam Markowitz的回答之后,这里是一个通用的方法(相对)简单地将组合框的 ItemSource 值设置为 enums ,同时向用户显示'Description'属性 . (你认为每个人都希望这样做,以便它可以成为一个班轮,但它只是没有发现) . [1399281_) .

    首先,创建这个简单的类,将任何Enum值转换为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;
        }
    }
    

    其次,在 OnLoad 事件处理程序中,您需要根据 Enum 类型中的每个 Enum 将组合框的源设置为 ComboEnumItems 的列表 . 这可以通过Linq实现 . 然后只需设置 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";
        }
    

    现在,用户将从用户友好列表 Descriptions 中进行选择,但他们选择的是您可以在代码中使用的 enum 值 . 要在代码中访问用户的选择, comboBoxUserReadable.SelectedItem 将是 ComboEnumItemcomboBoxUserReadable.SelectedValue 将是 EMyEnum .

  • 4

    我有同样的问题,我做的是添加一个新的 ComboBox 只有相同的索引中的值然后第一个,然后当我更改主要组合时,第二个中的索引同时更改,然后我采取第二个组合的值并使用它 .

    这是代码:

    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;
    }
    
  • 11

    class 创造:

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

    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);
    
            }
    
        }
    }
    
  • 3

    这是Visual Studio 2013的工作方式:

    单项:

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

    多个项目:

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

    无需进行类覆盖或包含任何其他内容 . 是的 comboBox1->SelectedItemcomboBox1->SelectedIndex 来电仍然有效 .

  • 21

    这类似于其他一些答案,但是紧凑并且如果您已经有列表,则避免转换为字典 .

    给定一个Windows窗体上的 ComboBox "combobox"和一个带有 string 类型属性 Name 的类 SomeClass

    List<SomeClass> list = new List<SomeClass>();
    
    combobox.DisplayMember = "Name";
    combobox.DataSource = list;
    

    这意味着SelectedItem是来自 listSomeClass 对象, combobox 中的每个项目都将使用其名称显示 .

  • 6

    对于Windows窗体,这是一个非常简单的解决方案,如果需要的话,最终值为(字符串) . 项目的名称将显示在组合框中,并且可以轻松比较所选值 .

    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;
    

    并在事件处理程序中获取所选值的值(字符串)

    string test = testComboBox.SelectedValue.ToString();
    
  • 0

    更好的解决方案;

    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";
    

    回归数据

    MessageBox.Show(cmbUser.SelectedValue.ToString());
    

相关问题