我有一个以可变数量的列开头的ListView,以及使用以下内容插入其中的项目的数组列表:
for (int x = 0; x < arrayList.Count; x++)
{
ListViewItem item = new ListViewItem("IF");
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)//Set rest of row cells ""
item.SubItems.Add("");
listView5.Items.Add(item);
}
我想在每次迭代时将下一行移到右边的x + 1个空值。但我似乎无法使其工作,我将不得不添加条件语句并手动输入它们,考虑到arraylist不是静态的,这是不切实际的:
if (x == 1)
{
ListViewItem item = new ListViewItem("IF");
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)
item.SubItems.Add("");
listView5.Items.Add(item);
}
else if(x==2)
{
ListViewItem item = new ListViewItem("");
item.SubItems.Add("IF");
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)
item.SubItems.Add("");
listView5.Items.Add(item);
}
else if(x==3)
{
ListViewItem item = new ListViewItem("");
item.SubItems.Add("");
item.SubItems.Add("IF");
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)
item.SubItems.Add("");
listView5.Items.Add(item);
} ..etc
如果我尝试访问下一个行单元格并将其设置如下:
ListViewItem item = new ListViewItem("IF");
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)
item.SubItems.Add("");
listView5.Items.Add(item);
listView5.Items[x + 1].SubItems[x].Text = "";
我收到运行时错误:
InvalidArgument =&#39; 2&#39;的值不适用于&#39; index&#39;。
是否有更简单的方法使用ListView控件或任何其他方法实现它?
答案 0 :(得分:0)
您遇到了一个非常常见的数组边界问题。让我给你一个代码示例来帮助......
static void Main(string[] args)
{
var tempList = new List<string>();
tempList.Add("1");
tempList.Add("2");
int x;
for (x = 0; x < tempList.Count; x++)
{
//do something here
}
//value of x after loop
Console.WriteLine(x);
//the value of x is 2.
try
{
Console.WriteLine(tempList[x]); //lets try to read the value here
}catch(Exception e){
Console.WriteLine("nope, not happening");
}
//to drive this point further home... let me show you what you did...
tempList.Add("random");
try
{
Console.WriteLine(tempList[x+1]); //lets try to read the value here after we added an element
}
catch (Exception e)
{
Console.WriteLine("nope, not happening");
}
Console.ReadLine();
}
答案 1 :(得分:0)
如果我理解正确,你可以通过另一个添加空子项的循环来实现这个目的:
for (int x = 0; x < arrayList.Count; x++)
{
//if x is 0 it's the first iteration so we want "IF"; otherwise we want ""
ListViewItem item = new ListViewItem(x == 0 ? "IF" : "");
//add the rest of the empty sub-elements with a loop
for (int y = 1; y < x; y++)
{
item.SubItems.Add("");
}
item.SubItems.Add("ID");
item.SubItems.Add("EX");
item.SubItems.Add("MEM");
item.SubItems.Add("WB");
for (int k = 5; k < ccNum; k++)//Set rest of row cells ""
item.SubItems.Add("");
listView5.Items.Add(item);
}