问题
I am trying to make a Move Up Button, and a Move Down Button, to move a selected item in a ListBox in Microsoft Visual Studio 2012. I have seen other examples in WDF, jquery, winforms, and some other forms but I haven't seen examples from Microsoft Visual Studio yet.
I have tried something like this:
listBox1.AddItem(listBox1.Text, listBox1.ListIndex - 1);
But Microsoft Visual Studio didn't have an "AddItem" property in their ListBoxes.
For more information, I have two listboxes that I want to make my Move up and down Buttons work with; the SelectedPlayersListBox, and the AvailablePlayersListBox. Will someone be kind enough to give me examples of a Move Up and Down button in Microsoft Visual Studio? Thank you.
回答1:
Sarcasm-free answer. Enjoy
private void btnUp_Click(object sender, EventArgs e)
{
MoveUp(ListBox1);
}
private void btnDown_Click(object sender, EventArgs e)
{
MoveDown(ListBox1);
}
void MoveUp(ListBox myListBox)
{
int selectedIndex = myListBox.SelectedIndex;
if (selectedIndex > 0)
{
myListBox.Items.Insert(selectedIndex - 1, myListBox.Items[selectedIndex]);
myListBox.Items.RemoveAt(selectedIndex + 1);
myListBox.SelectedIndex = selectedIndex - 1;
}
}
void MoveDown(ListBox myListBox)
{
int selectedIndex = myListBox.SelectedIndex;
if (selectedIndex < myListBox.Items.Count - 1 & selectedIndex != -1)
{
myListBox.Items.Insert(selectedIndex + 2, myListBox.Items[selectedIndex]);
myListBox.Items.RemoveAt(selectedIndex);
myListBox.SelectedIndex = selectedIndex + 1;
}
}
回答2:
You are looking for ListBox.Items.Add()
For the move-up, something like this should work:
void MoveUp()
{
if (listBox1.SelectedItem == null)
return;
var idx = listBox1.SelectedIndex;
var elem = listBox1.SelectedItem;
listBox1.Items.RemoveAt(idx);
listBox1.Items.Insert(idx - 1, elem);
}
for move down, just change idx - 1
to idx + 1
来源:https://stackoverflow.com/questions/15748949/move-up-move-down-buttons-for-listboxes-in-visual-studio