使用值和Text在组合框中添加更多的comboboxItem

时间:2013-03-27 16:58:18

标签: c# combobox

我创建了一个名为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)但是如何更改代码,他总是可以添加新的组合框?

谢谢!

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);
        }

答案 2 :(得分: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);

答案 3 :(得分:0)

列出ComboBoxItems,将项目添加到列表中,并将comboBox1的DataSource设置为列表:

    List<ComboBoxItem> Items = new List<ComboBoxItem>();
    comboBox1.DataSource = Items;

答案 4 :(得分: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,您实际上正在替换和覆盖旧值。