简体   繁体   English

将具有多个值的项目添加到组合框C#

[英]Add items to combobox with multiple values C#

currently I have a combobox with three hard coded items. 目前,我有一个带有三个硬编码项目的组合框。 Each item carries 2 values. 每个项目带有2个值。 I'm using a switch case statement to get the values for each item depending on which item is selected. 我正在使用switch case语句来获取每个项目的值,具体取决于选择了哪个项目。

Switch(combobox.selectedindex)
{
    case 0: // Item 1 in combobox
        a = 100;
        b = 0.1;
        break;
    case 1: // Item 2 in combobox
        a = 300;
        b = 0.5;
        break;
    //and so on....
}

I'm trying to add a feature to allow the user to add more items into the combobox with inputted a and b values. 我正在尝试添加一项功能,以允许用户使用输入的a和b值将更多项目添加到组合框中。 How would i be able to dynamically add case statements and define the values under each case condition? 我如何能够动态添加案例陈述并在每种案例条件下定义值? I've had a look at using a datatable instead but I don't know how to get multiple valuemembers out of the datatable when one item is selected. 我曾经看过使用数据表,但是当选择一项时,我不知道如何从数据表中获取多个值成员。

Also, I would like to save the user added items and it's corresponding values to a .dat file. 另外,我想将用户添加的项目及其对应的值保存到.dat文件中。 So when the program is re-opened it will be able to load the list of items added by the user from the file. 因此,当重新打开程序时,它将能够从文件中加载用户添加的项目列表。 I considered using streamwriter and readline for this but I'm unsure how it would be done. 我考虑过为此使用streamwriter和readline,但不确定如何实现。

You can use Binding on a combobox using the DataSource. 您可以使用数据源在组合框上使用绑定。 The ComboBox can also be bound to other things than Primitive values (string/int/hardcoded values). ComboBox还可以绑定到除原始值(字符串/整数/硬编码值)之外的其他内容。 So you could make a small class that represents the values you are setting in your switch statement, and then use the DisplayMember to say which property should be visible in the combobox. 因此,您可以创建一个小类来表示要在switch语句中设置的值,然后使用DisplayMember来说出哪个属性在组合框中可见。

An example of such a basic class could be 这样的基本类的一个例子是

public class DataStructure
{
    public double A { get; set; }

    public int B { get; set; }

    public string Title { get; set; }
}

Since you are talking about users adding values to the combobox dynamically, you could use a BindingList that contains the separate classes, this BindingList could be a protected field inside your class, to which you add the new DataStructure when the user adds one, and then automatically updates the combobox with the new value you added. 由于您是在谈论用户动态地向组合框添加值,因此可以使用包含单独类的BindingList,此BindingList可以是类内部的受保护字段,当用户添加新的DataStructure时,您可以在其中添加新的DataStructure自动使用您添加的新值更新组合框。

The setup of the ComboBox, can be done in either Form_Load, or in the Form Constructor (after the InitializeComponent() call), like such: 可以在Form_Load或Form构造函数中(在InitializeComponent()调用之后)完成ComboBox的设置,例如:

// your form
public partial class Form1 : Form
{
    // the property contains all the items that will be shown in the combobox
    protected IList<DataStructure> dataItems = new BindingList<DataStructure>();
    // a way to keep the selected reference that you do not always have to ask the combobox, gets updated on selection changed events
    protected DataStructure selectedDataStructure = null;

    public Form1()
    {
        InitializeComponent();
        // create your default values here
        dataItems.Add(new DataStructure { A = 0.5, B = 100, Title = "Some value" });
        dataItems.Add(new DataStructure { A = 0.75, B = 100, Title = "More value" });
        dataItems.Add(new DataStructure { A = 0.95, B = 100, Title = "Even more value" });
        // assign the dataitems to the combobox datasource
        comboBox1.DataSource = dataItems;
        // Say what the combobox should show in the dropdown
        comboBox1.DisplayMember = "Title";
        // set it to list only, no typing
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        // register to the event that triggers each time the selection changes
        comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
    }

    // a method to add items to the dataItems (and automatically to the ComboBox thanks to the BindingContext)
    private void Add(double a, int b, string title)
    {
        dataItems.Add(new DataStructure { A = a, B = b, Title = title });
    }

    // when the value changes, update the selectedDataStructure field
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox combo = sender as ComboBox;
        if (combo == null)
        {
            return;
        }
        selectedDataStructure = combo.SelectedItem as DataStructure;
        if (selectedDataStructure == null)
        {
            MessageBox.Show("You didn't select anything at the moment");
        }
        else
        {
            MessageBox.Show(string.Format("You currently selected {0} with A = {1:n2}, B = {2}", selectedDataStructure.Title, selectedDataStructure.A, selectedDataStructure.B));
        }
    }

    // to add items on button click
    private void AddComboBoxItemButton_Click(object sender, EventArgs e)
    {
        string title = textBox1.Text;
        if (string.IsNullOrWhiteSpace(title))
        {
            MessageBox.Show("A title is required!");
            return;
        }
        Random random = new Random();
        double a = random.NextDouble();
        int b = random.Next();
        Add(a, b, title);
        textBox1.Text = string.Empty;
    }
}

Like this, you have the selected item always at hand, you can request the values from the properties of the selected, and you don't have to worry about syncing the ComboBox with the items currently visible 这样,您总是可以随时使用选定的项目,可以从选定的属性中请求值,而不必担心将ComboBox与当前可见的项目进行同步

From the documentation : 文档中

Although the ComboBox is typically used to display text items, you can add any object to the ComboBox. 尽管ComboBox通常用于显示文本项,但是您可以将任何对象添加到ComboBox。 Typically, the representation of an object in the ComboBox is the string returned by that object's ToString method. 通常,ComboBox中对象的表示形式是该对象的ToString方法返回的字符串。 If you want to have a member of the object displayed instead, choose the member that will be displayed by setting the DisplayMember property to the name of the appropriate member. 如果要改为显示该对象的成员,请通过将DisplayMember属性设置为适当成员的名称来选择将要显示的成员。 You can also choose a member of the object that will represent the value returned by the object by setting the ValueMember property. 您还可以通过设置ValueMember属性来选择将代表该对象返回值的对象成员。 For more information, see ListControl. 有关更多信息,请参见ListControl。

So you can just add objects that hold all the information, directly to the Items collection of the ComboBox. 因此,您可以直接将包含所有信息的对象添加到ComboBox的Items集合中。 Later, retrieve the SelectedItem property and cast it back to the correct type. 以后,检索SelectedItem属性并将其强制转换回正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM