2013-03-27 59 views
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; 
    } 

} 

现在我想喜欢每次值和文本添加到comboboxitem

事情是这样的:

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)但如何改变他总是可以添加新组合框的代码?

谢谢!

+0

主要是因为我很好奇......为什么你所评论的代码不工作?它看起来完全像它应该的,并且应该工作得很好。你需要其他地方的busstops变量吗?在这种情况下,你应该使它成为某种类型的集合或列表,而不是单个变量......并且包含不同的问题以及...... – Nevyn 2013-03-27 17:04:05

回答

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); 
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); 
     } 
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); 
0

让ComboBoxItems的列表,添加项目到列表中,并设置数据源comboBox1到列表:

List<ComboBoxItem> Items = new List<ComboBoxItem>(); 
    comboBox1.DataSource = Items; 
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,你实际上正在取代和覆盖旧的价值。

+0

哇,在我花时间写这篇文章的时候,5个答案是产生.... – Nevyn 2013-03-27 17:02:38