当用户尝试在列表框中向下移动最后一项时,我需要一个消息框来显示该项目已在底部。该应用程序允许用户输入更多项目到列表,所以当达到一个数字时显示消息,如顶部,将无法工作,这是我目前的代码:
private void MoveUpButton()
{
if (selectedPlayersListBox.SelectedItem == null || selectedPlayersListBox.SelectedIndex < 0)
MessageBox.Show("A player under \"Selected Players\" must be selected");
if (selectedPlayersListBox.SelectedIndex == 0)
MessageBox.Show("Player is already at the top of the list.");
else
{
MoveItem(-1);
}
}
private void MoveDownButton()
{
if (selectedPlayersListBox.SelectedItem == null || selectedPlayersListBox.SelectedIndex < 0)
MessageBox.Show("A player under \"Selected Players\" must be selected");
else
{
MoveItem(1);
}
}
private void MoveItem(int direction)
{
int newIndex = selectedPlayersListBox.SelectedIndex + direction;
if (newIndex < 0 || newIndex >= selectedPlayersListBox.Items.Count)
return;
object selected = selectedPlayersListBox.SelectedItem;
selectedPlayersListBox.Items.Remove(selected);
selectedPlayersListBox.Items.Insert(newIndex, selected);
selectedPlayersListBox.SetSelected(newIndex, true);
}
正如我上面提到的,MoveUpButton运行正常,但MoveDownButton给我带来了麻烦。
感谢您提供的任何帮助。
答案 0 :(得分:2)
它看起来就像MoveUpButton,除了你要检查SelectedIndex是否等于Count - 1:
private void MoveDownButton()
{
if (selectedPlayersListBox.SelectedItem == null || selectedPlayersListBox.SelectedIndex < 0)
MessageBox.Show("A player under \"Selected Players\" must be selected");
else if (selectedPlayersListBox.SelectedIndex == selectedPlayersListBox.Items.Count - 1)
MessageBox.Show("Player is already at the bottom of the list.");
else
{
MoveItem(1);
}
}
答案 1 :(得分:0)
向上/向下移动的另一种方式
public partial class Form1:Form {
public Form1() {
InitializeComponent();
btnMoveUp.Enabled = false;
btnMoveDown.Enabled = false;
}
private void lstPlayers_SelectedIndexChanged(object sender, EventArgs e) {
btnMoveUp.Enabled = (lstPlayers.SelectedIndex != 0);
btnMoveDown.Enabled = (lstPlayers.SelectedIndex != lstPlayers.Items.Count - 1);
}
private void btnMoveUp_Click(object sender, EventArgs e) {
var index = lstPlayers.SelectedIndex;
var item = lstPlayers.SelectedItem;
lstPlayers.Items.Insert(index - 1, item);
lstPlayers.Items.RemoveAt(index + 1);
lstPlayers.SetSelected(index - 1, true);
}
private void btnMoveDown_Click(object sender, EventArgs e) {
var index = lstPlayers.SelectedIndex;
var item = lstPlayers.SelectedItem;
lstPlayers.Items.Insert(index + 2, item);
lstPlayers.Items.RemoveAt(index);
lstPlayers.SetSelected(index + 1, true);
}
}