C#-列表框不显示项目
本文关键字:显示 项目 列表 C#- | 更新日期: 2023-09-27 18:25:25
我正在开发一个程序,它可以作为停车场模拟器。我希望用户界面显示在任何给定时间每个级别上有多少可用空间。我曾尝试使用列表框(一个用于级别号,一个用于该级别上的空间数)来实现这一点,但无法实现。出于某种原因,显示可用空间(listboxSA
)的列表框总是显示为空,我不知道为什么。
创建列表框的代码如下所示:
public void updateLevelLabels(Simulator simulator)
{
//constant integers used for label positioning
//y coordinate for first label
const int YSTARTPOINT = 12;
//x coordinate for all labels
const int XSTARTPOINT = 104;
//create new listbox to show level IDs
ListBox listboxLevels = new ListBox();
//position listbox on form
//constant x-coordinate
listboxLevels.Left = XSTARTPOINT;
//constant y-coordinate
listboxLevels.Top = YSTARTPOINT;
//auto-assumes size depending on content
listboxLevels.AutoSize = true;
//create new listbox to show spaces available
ListBox listboxSA = new ListBox();
//set x and y coordinates
//constant x coordinate
listboxSA.Left = XSTARTPOINT + 38;
//constant y coordinate
listboxSA.Top = YSTARTPOINT;
//auto-resizes depending on content
listboxSA.AutoSize = true;
//populate listboxes
for (int i = 0; i < Length(); i++)
{
//identify level at current index
Level lev = At(i);
//add level unique ID to list
listboxLevels.Items.Add(lev.getLevelID());
//add number of spaces (available) on level to list
listboxSA.Items.Add(lev.getNumSpaces().ToString());
}
//place listboxes on form
simulator.Controls.Add(listboxLevels);
simulator.Controls.Add(listboxSA);
}
我已经调试了代码,lev.numSpaces变量的值是我所期望的。我还尝试在listboxSA
创建后选择它的索引,并且创建的索引是可选的(列表框项目变为高亮显示),但其中仍然没有文本。
老实说,我不知道是什么原因导致了这种情况的发生,特别奇怪的是,考虑到相同的过程本质上是用differenet()函数在两个列表框上执行的。
如果有人能发现可能会把它扔掉的东西,我真的很感激任何建议!
被调用函数的代码如下所示:
//from `Levels` class
//Levels acts as a public interface for a `List<Level>`
public int Length()
{
//return number of `Level` instances in collection (int)
return levelList.Count;
}
//from `Level` class
//obtain unique identifer of level
public string getLevelID()
{
//return unique Level name
return levelID;
}
//from `Level` class
//obtain number of spaces on level
//all spaces assumed to be free
public int getNumSpaces()
{
//should = value of Levels.Length()
return numSpaces;
}
提前感谢
标记
您应该更好地检查您试图应用到列表框的数据,或者在其他地方查找问题。我做了一个测试,它和你的代码做得一样,没有问题。
string[] stringArray = new string[] { "one", "two", "three", "four" };
int[] intArray = new int[] { 1, 2, 3, 4 };
private void Addlistboxes()
{
ListBox lb1 = new ListBox();
ListBox lb2 = new ListBox();
lb1.Left = 10;
lb1.Top = 60;
lb1.AutoSize = true;
lb2.Left = 15 + lb1.Width;
lb2.Top = 60;
lb2.AutoSize = true;
for (int i = 0; i < 4; i++)
{
lb1.Items.Add(stringArray[i]);
lb2.Items.Add(intArray[i]);
}
this.Controls.Add(lb1);
this.Controls.Add(lb2);
}`