gpt4 book ai didi

c# - 在 C# 中使用 List 字符串的 listview 显示错误

转载 作者:行者123 更新时间:2023-11-30 16:18:57 25 4
gpt4 key购买 nike

我在 C# WinForms 中有一个 listView1,它显示 2 个列表

List<string> pths;
List<string> rec;

public void Disp ()
{

DisplayListInColumns(listView1, pths, 0);
DisplayListInColumns(listView1, rec, 1);
}
private static void DisplayListInColumns(ListView listView, List<string> values, int columnIndex)
{
for (int index = 0; index < values.Count; index++)
{
while (index >= listView.Items.Count)
{
listView.Items.Add(new ListViewItem());
}
ListViewItem listViewItem = listView.Items[index];
while (listViewItem.SubItems.Count <= columnIndex)
{
listViewItem.SubItems.Add(new ListViewItem.ListViewSubItem());
}
listViewItem.SubItems[columnIndex].Text = values[index];
}
}

我正在使用全局 List 进行更改并将其显示在 listview1 中,但只有在用户单击 apply_button 后才会保存更改(保存到 xml 中)。

“编辑和添加详细信息”按钮工作正常并且显示完美。但是当我删除数据时,会抛出一个错误。

下面是删除 Action :

//Configuration - DELETE button
private void button6_Click(object sender, EventArgs e)
{
string select = null;

if (listView1.SelectedItems.Count > 0)
{
select = (listView1.SelectedItems[0].Text);
}
int count = listView1.SelectedItems[0].Index;

if (select != null)
{
pths.RemoveAt(count);
rec.RemoveAt(count);
string s = String.Join("; ", pths.ToArray());
string r = String.Join("; ", rec.ToArray());
//MessageBox.Show(s);
//MessageBox.Show(r);
}
Disp();
}

我想经过几次尝试,我的索引出错了。即使在删除之后,在调试时我也得到 listView.Items.Count = 5.我猜计数仍然是 5(示例 - 列表中的 5 个字符串)删除后它应该减少到 4 并且索引相应地减少到 0-3。我收到以下错误

ArgumentOutOfRangeException at pths.RemoveAt(count)
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

作为替代方案,我尝试了 pths.Remove(select); 但没有解决这个问题。

如有任何帮助,我们将不胜感激。谢谢

最佳答案

改变你的if语句

if (select != null)

对此

if(!string.IsNullOrWhiteSpace(select))

您的文本属性不会为 null,它将是空字符串,因此当您认为自己不是时,您正在进入该部分。

编辑:

根据您的评论,我将引导您使用此解决方案,将您的整个删除功能替换为如下内容:

private void button6_Click(object sender, EventArgs e)
{
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
listView1.Items.Remove(eachItem);
if (pths.Any(o => o == eachItem.Text))
{
pths.Remove(eachItem.Text);
}
if (rec.Any(o => o == eachItem.Text))
{
rec.Remove(eachItem.Text);
}
}
}

您可能需要 eachItem.Value,但我认为 .Text 会起作用。

注意:这个答案我完全是从这里复制的(我不相信这个解决方案):

Remove the Selected Item From ListView

关于c# - 在 C# 中使用 List 字符串的 listview 显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666703/

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