【发布时间】:2015-02-12 12:34:10
【问题描述】:
这是一个连接到服务器、获取表并将它们转换为 drop create SQL 脚本的 Windows 窗体应用程序。有两个列表框,lbSource 加载初始表列表,lbTarget 包含用户移到那里导出的表。
出现的问题是,如果我移动最后一个剩余项(selIndex = 0),则没有剩余项可以选择(lbTarget.SetSelected(selIndex, true);) selIndex 得到一个值,但列表框是空的(OutOfRange)。
我需要(selIndex >= 0) 的代码来选择下一个项目(如果它位于列表顶部(also selIndex = 0))。
所以我尝试做的是检查(listBox.Items.Count == 0),但这似乎不起作用。
这是如果您单击按钮以将 (a) 某些项目从一个列表框移动到另一个列表框时发生的情况的代码。源代码到目标代码相同。
private void cmdTargetToSource_Click(object sender, EventArgs e)
{
//move more than one item
lbTarget.SelectionMode = SelectionMode.MultiSimple;
//sorting the lists
lbSource.Sorted = true;
lbTarget.Sorted = true;
//save the selectedIndex
int selIndex = lbTarget.SelectedIndex;
if (lbTarget.SelectedIndex == -1)
{
return;
}
//moving last entry in listBox sets selIndex higher than lbTarget.Items.Count
if (selIndex < lbTarget.Items.Count)
{
selIndex = selIndex - 1;
}
if (selIndex == -1)
{
selIndex = selIndex + 1;
}
//If there are no items left do nothing
if (lbTarget.Items.Count == 0)
{
return;
}
if (selIndex == lbTarget.Items.Count -2)
{
selIndex = selIndex - 1;
}
MoveListBoxItems(lbTarget, lbSource);
//select next item
if (selIndex >= 0)
{
lbTarget.SetSelected(selIndex, true);
}
//selectionmode back to single selection
lbTarget.SelectionMode = SelectionMode.One;
}
【问题讨论】:
-
你为什么只做
IF语句?为什么不能使用IF ELSE?