【问题标题】:Add items to combobox with multiple values C#将项目添加到具有多个值的组合框 C#
【发布时间】:2015-03-21 01:00:47
【问题描述】:

目前我有一个包含三个硬编码项目的组合框。 每个项目带有 2 个值。我正在使用 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....
}

我正在尝试添加一项功能,以允许用户使用输入的 a 和 b 值将更多项目添加到组合框中。我如何能够动态添加 case 语句并在每个 case 条件下定义值?我已经看过使用数据表,但我不知道如何在选择一个项目时从数据表中获取多个值成员。

另外,我想将用户添加的项目及其对应值保存到 .dat 文件中。因此,当程序重新打开时,它将能够从文件中加载用户添加的项目列表。我考虑过为此使用 streamwriter 和 readline,但我不确定如何完成。

【问题讨论】:

  • 将值存储在一个类中,为列表框创建一个List<YourClass> 数据源,然后评估myList[SelectedIndex] 以获取(或设置)这些值。

标签: c# winforms combobox


【解决方案1】:

您可以使用 DataSource 对组合框使用绑定。 ComboBox 还可以绑定到原始值(字符串/int/硬编码值)以外的其他事物。因此,您可以创建一个小类来表示您在 switch 语句中设置的值,然后使用 DisplayMember 来说明哪个属性应该在组合框中可见。

这样一个基本类的例子可以是

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

    public int B { get; set; }

    public string Title { get; set; }
}

由于您正在谈论用户向组合框动态添加值,因此您可以使用包含单独类的 BindingList,此 BindingList 可以是类中的受保护字段,当用户添加新的 DataStructure 时,您可以将新的 DataStructure 添加到该字段中,然后使用您添加的新值自动更新组合框。

ComboBox 的设置,可以在 Form_Load 中完成,也可以在 Form Constructor 中完成(在 InitializeComponent() 调用之后),如下所示:

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

像这样,您始终拥有选定的项目,您可以从选定的属性中请求值,并且您不必担心将 ComboBox 与当前可见的项目同步

【讨论】:

  • 使用基本的Items 集合可以完成很多工作
  • 有很多 cmets :) 我认为有更多东西可以学习总是不错的 :D
【解决方案2】:

来自the documentation

虽然 ComboBox 通常用于显示文本项,但您可以将任何对象添加到 ComboBox。通常,ComboBox 中对象的表示形式是该对象的 ToString 方法返回的字符串。如果您希望显示对象的成员,请通过将 DisplayMember 属性设置为相应成员的名称来选择将显示的成员。您还可以通过设置 ValueMember 属性来选择将表示对象返回值的对象成员。有关详细信息,请参阅 ListControl。

因此,您可以将包含所有信息的对象直接添加到组合框的Items 集合中。稍后,检索 SelectedItem 属性并将其转换回正确的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多