【发布时间】:2021-11-23 04:54:35
【问题描述】:
我有一个场景,我有三个列表框。可以在列表框中选择多个项目。 根据一个列表框中的项目选择,我需要在其他列表框中选择和取消选择相应的行。
我有下面的代码,但我遗漏了一些东西。 当我选择和取消选择项目时,它会错误地选择和取消选择其他行项目。
for (int count = 0; count < listBox_1.SelectedIndices.Count; count++)
{
// Determine if the item is selected.
if (listBox_1.GetSelected(count) == true)
{
listBox_2.SetSelected(listBox_1.SelectedIndices[count], false);
listBox_3.SetSelected(listBox_1.SelectedIndices[count], false);
}
else if (listBox_1.GetSelected(count) == false)
{
// Select all items that are not selected.
listBox_2.SetSelected(listBox_1.SelectedIndices[count], true);
listBox_3.SetSelected(listBox_1.SelectedIndices[count], true);
}
}
这里 LB1 中的项目选择应该控制 LB2 和 LB3 中的选择。 现在,由于在 LB1 中选择了第 2 和第 3 项 - 在 LB2 和 LB3 中也应选择第 2 和第 3 项。但事实并非如此。
========================================= 更新
当用户选择 ListBox2 或 ListBox3 中的项目时,我如何复制该行为
private void listBox_1_SelectedIndexChanged_(object sender, EventArgs e)
{
listBox_2.ClearSelected();
listBox_3.ClearSelected();
int userSelectedIndex = listBox_1.Items.Count;
if (listBox_1.SelectedIndices.Count > 0)
{
for (int count = 0; count < listBox_1.Items.Count; count++)
{
// Determine if the item is selected.
if (listBox_1.GetSelected(count) == true)
{
if (count <= listBox_2.Items.Count)
listBox_2.SetSelected(count, true);
if (count <= listBox_3.Items.Count)
listBox_3.SetSelected(count, true);
}
else if (listBox_1.GetSelected(count) == false)
{
// Select all items that are not selected.
if (count <= listBox_2.Items.Count)
listBox_2.SetSelected(count, false);
if (count <= listBox_3.Items.Count)
listBox_3.SetSelected(count, false);
}
}
}
}
当用户选择 ListBox 2 中的项目时,LB1 和 LB3 中的项目也应该被选中。
private void listBox_2_SelectedIndexChanged(object sender, EventArgs e)
{
listBox_1.ClearSelected(); // ITS giving error here.
listBox_3.ClearSelected();
int userSelectedIndex = listBox_2.Items.Count;
if (listBox_2.SelectedIndices.Count > 0)
{
for (int count = 0; count < listBox_2.Items.Count; count++)
{
// Determine if the item is selected.
if (listBox_2.GetSelected(count) == true)
{
if (count <= listBox_1.Items.Count)
listBox_1.SetSelected(count, true);
if (count <= listBox_3.Items.Count)
listBox_3.SetSelected(count, true);
}
else if (listBox_2.GetSelected(count) == false)
{
// Select all items that are not selected.
if (count <= listBox_1.Items.Count)
listBox_1.SetSelected(count, false);
if (count <= listBox_3.Items.Count)
listBox_3.SetSelected(count, false);
}
}
}
}
【问题讨论】:
-
“但我错过了一些东西。” ...不是问题。什么没有按预期工作?
-
@JohnG - 更新 - 它错误地选择和取消选择其他行项目。
-
好的,我认为这更清楚了。当用户选择/取消选择列表框 1 中的一行时,什么会被认为是“正确的”?什么会被认为是“不正确的”?当另一个列表框中的另一行被选择/取消选择时,我们不知道是什么决定了应该选择/取消选择哪个列表框行。你能举个例子吗?
-
@JohnG - 更新了一个例子。希望这会有所帮助。
-
或者简单地使用
foreach循环遍历SelectedIndicies集合。类似...foreach (int selectedIndex in listBox_1.SelectedIndices) { ......发布的代码在哪里被调用?