Add items to combobox with multiple values C#

一曲冷凌霜 提交于 2021-01-28 10:56:44

问题


currently I have a combobox with three hard coded items. Each item carries 2 values. I'm using a switch case statement to get the values for each item depending on which item is selected.

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. 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. 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.


回答1:


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

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.

The setup of the ComboBox, can be done in either Form_Load, or in the Form Constructor (after the InitializeComponent() call), like such:

// 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




回答2:


From the documentation:

Although the ComboBox is typically used to display text items, you can add any object to the ComboBox. Typically, the representation of an object in the ComboBox is the string returned by that object's ToString method. 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. You can also choose a member of the object that will represent the value returned by the object by setting the ValueMember property. For more information, see ListControl.

So you can just add objects that hold all the information, directly to the Items collection of the ComboBox. Later, retrieve the SelectedItem property and cast it back to the correct type.



来源:https://stackoverflow.com/questions/29178057/add-items-to-combobox-with-multiple-values-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!