[英]Why when adding items to a combobox the values are the same and not increasing by the loop?
ComboboxItem boxitem = new ComboboxItem();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 100; i++)
{
boxitem.Text = i.ToString();
comboBox1.Items.Add(boxitem);
}
}
And the class ComboboxItem : 和类ComboboxItem:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
But for some reason all the items in the comboBox1 are 99 There are 100 items all of them the same 99 Instead 1 2 3 4 5 6 7 .... 99 但是由于某种原因,comboBox1中的所有项目都是99。有100个项目全部相同99而是1 2 3 4 5 6 7 .... 99
Here you are setting the text of the same ComboBox
item over and over and adding it to your list: 在这里,您要一遍又一遍地设置同一ComboBox
项的文本,并将其添加到列表中:
for (int i = 0; i < 100;
{
boxitem.Text = i.ToString();
comboBox1.Items.Add(boxitem);
}
Instead, create a new ComboBox
inside the loop and add that to the list. 而是在循环内创建一个新的ComboBox
并将其添加到列表中。 Just move the 只需移动
ComboboxItem boxitem = new ComboboxItem();
inside your for-loop, and you're good. 在for循环中,您就很好。
it is that you are changing the text of a single item, instead of instantiating a new one with each iteration. 这是因为您要更改单个项目的文本,而不是每次迭代都实例化一个新项目。 This should fix it: 这应该解决它:
ComboboxItem boxitem = new ComboboxItem();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 100; i++)
{
//added bit follows here
boxitem = new ComboboxItem();
boxitem.Text = i.ToString();
comboBox1.Items.Add(boxitem);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.