gpt4 book ai didi

c# - ListView.SelectedItems[0] 选择错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:53 24 4
gpt4 key购买 nike

为什么我的程序返回以下错误?

请具体点谢谢

PS:无论出于何种原因,当 listview 中只有一项时,它会起作用。

Error: InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index

代码:

if(e.Control == true)
{
try
{
string s = "";
string sCheck = "";
int select = 0;
int i = 0;
int position = 0;

if (i == 1)
{
i--;
}

if(select >= 1)
{
do
{
select--;
} while (select >= 1);
}

if (position >= 1)
{
do
{
position--;
} while (position >= 1);
}

foreach (object item1 in listView1.Items)
{
if (item1 == listView1.SelectedItems[select])
{
s = listView1.SelectedItems[select].Text;
sCheck = item1.ToString();
MessageBox.Show(item1.ToString());

}
else
{
select++;
}
}
string s1 = "";


foreach (object item in listView1.Items)
{
if (sCheck == item.ToString())
{

MessageBox.Show(item.ToString());
i++;
position++;

}
else
{
position++;
}
}

string s2 = listView1.Items.Count.ToString();
s1 = position.ToString();

if (i == 1)
{
string result = "Item: " + s + " || Position: " + s1 + " || Total Items: " + s2;
MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);

}

最佳答案

如果没有选定的项目,代码将在 if (item1 == listView1.SelectedItems[select]) 处抛出异常,因为在 [0] 处没有元素> 在集合中。

此外,我相信以下代码会产生与您的代码相同的结果:

try
{
foreach (var item in listView1.SelectedItems)
{
MessageBox.Show(item.ToString());
}

if (listView1.SelectedItems.Count == 1)
{
var result = string.Format("Item: {0} || Position: {1} || Total Items: {2}",
listView1.SelectedItems[0], listView1.SelectedItems.Count, listView1.Items.Count);

MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);
}

前三个 if 语句是多余的,因为它们直接发生在变量赋值之后(即,如果刚刚将它初始化为 0,i 怎么可能等于 1 ?)

两个 foreach 循环显示相同的内容(显示包含所选项目的消息框)。

每个选定项目的位置都会增加,因此它始终等于选定项目的总数。

如果您提供更多关于您想要实现的目标的详细信息,我会尽力提供帮助。

关于c# - ListView.SelectedItems[0] 选择错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com