0

我创建了一个名为 ComboBoxitem 的自己的类,它有两个道具:值和文本。

public class ComboBoxItem
{
    public string Value;

    public string Text;

    public ComboBoxItem(string val, string text)
    {

        Value = val;

        Text = text;
    }
    public override string ToString()
    {
        return Text;
    }

}

现在我想每次都向组合框项添加一个值和一个文本

像这样的东西:

public ComboBoxItem busstops;

        private void Form1_Load(object sender, EventArgs e)
        {
            lblText.Text = "Timetable Bushours for " + "New Bridge Street-St Dominics";

            busstops = new ComboBoxItem("410000015503", "New Bridge Street-St Dominics");
            busstops = new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker ");

        /*    comboBox1.Items.Add(new ComboBoxItem ("410000015503", "New Bridge Street-St Dominics"));
            comboBox1.Items.Add(new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker "));*/


            comboBox1.Items.Add(busstops);
        }

但问题是只添加了最后一项(正常,因为我总是说新的 ComboboxItem)但是如何更改他总是可以添加新的组合框项的代码?

谢谢!

4

5 回答 5

1

两个 ComboBox 项都是不同的对象,因此您需要两个 ComboBox 变量来存储它们。

 busstops1 = new ComboBoxItem("410000015503", "New Bridge Street-St Dominics");
 busstops2 = new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker ");


 comboBox1.Items.Add(busstops1);
 comboBox1.Items.Add(busstops2);
于 2013-03-27T17:00:01.473 回答
0

comboBox1.Items每次更新busstops实例 时将其添加到。

        private void Form1_Load(object sender, EventArgs e)
        {
            lblText.Text = "Timetable Bushours for " + "New Bridge Street-St Dominics";

            busstops = new ComboBoxItem("410000015503", "New Bridge Street-St Dominics");
            comboBox1.Items.Add(busstops);

            busstops = new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker ");
            comboBox1.Items.Add(busstops);
        }
于 2013-03-27T17:01:02.890 回答
0

您应该在每次分配后添加。

        busstops = new ComboBoxItem("410000015503", "New Bridge Street-St Dominics");

        comboBox1.Items.Add(busstops); // Add this line

        busstops = new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker ");
        comboBox1.Items.Add(busstops);
于 2013-03-27T17:01:07.663 回答
0

制作一个 ComboBoxItems 列表,将项目添加到列表中,并将 comboBox1 的 DataSource 设置为列表:

    List<ComboBoxItem> Items = new List<ComboBoxItem>();
    comboBox1.DataSource = Items;
于 2013-03-27T17:01:43.280 回答
0
    private void Form1_Load(object sender, EventArgs e)
    {
        lblText.Text = "Timetable Bushours for " + "New Bridge Street-St Dominics";

        busstops = new ComboBoxItem("410000015503", "New Bridge Street-St Dominics");
        comboBox1.Items.Add(busstops);//add this line here

        busstops = new ComboBoxItem("410000015552", "Bothal Street (N-Bound), Byker ");
        comboBox1.Items.Add(busstops);//and again here
    }

由于您要添加相同的值,因此每次更改时都必须添加该值。通过声明new,您实际上是在替换和覆盖旧值。

于 2013-03-27T17:02:05.483 回答