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

238

在C# WinApp中,我该如何将文本和值同时添加到ComboBox的项中? 我进行了搜索,通常的答案都是使用“绑定到源代码”...但在我的情况下,我的程序中没有准备好的绑定源... 我应该如何实现这样的功能:

combo1.Item[1] = "DisplayText";
combo1.Item[1].Value = "useful Value"
21个回答

4

我喜欢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;

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

2
Adam Markowitz的回答之后,这里是一种通用的方法(相对简单),可以将组合框的ItemSource值设置为枚举,并向用户显示“描述”属性。 (你会认为每个人都想这样做,以便它成为{{link1:.NET}}一行代码,但实际上并不是这样,这是我找到的最优雅的方法)。
首先,创建这个简单的类,将任何枚举值转换为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类型中的每个EnumComboEnumItems列表。这可以通过使用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";
    }

现在用户将从您用户友好的“描述”列表中选择,但他们选择的将是您可以在代码中使用的“枚举”值。 要在代码中访问用户的选择,“comboBoxUserReadable.SelectedItem”将是“ComboEnumItem”,而“comboBoxUserReadable.SelectedValue”将是“EMyEnum”。

2

您可以使用通用类型:

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类型的示例:

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

最佳解决方案 - elle0087

1

类创建:

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

        }

    }
}

1
using (SqlConnection con = new SqlConnection(insertClass.dbPath))
{
    con.Open();
    using (SqlDataAdapter sda = new SqlDataAdapter(
    "SELECT CategoryID, Category FROM Category WHERE Status='Active' ", con))
    {
        //Fill the DataTable with records from Table.
        DataTable dt = new DataTable();
        sda.Fill(dt);
        //Insert the Default Item to DataTable.
        DataRow row = dt.NewRow();
        row[0] = 0;
        row[1] = "(Selecione)";
        dt.Rows.InsertAt(row, 0);
        //Assign DataTable as DataSource.
        cboProductTypeName.DataSource = dt;
        cboProductTypeName.DisplayMember = "Category";
        cboProductTypeName.ValueMember = "CategoryID";
    }
}             
con.Close();

1
你可以使用这段代码将一些带有文本和值的项目插入到组合框中。 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"/>

请解释一下你的解决方案。 - Vaibhav Bajaj
简单来说,将以下国家添加到它们各自的索引中,在运行时会出现一个下拉框。当您单击下拉框时,将显示其他以下选项。 - Muhammad Ahmad
2
这不适用于ID,这只是索引列表的一种方式,这不是问题所在。 - Mr Heelis

0

我曾经遇到过同样的问题,我的解决方法是添加一个新的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;
}

0

这是 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的调用仍然有效。


0

如果只需要最终值作为字符串,那么这是一个非常简单的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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接