1

我可能会对术语感到困惑,但这是我想要做的:

我有一个移动功能,最终将选定的项目从一个移动listBox到另一个。有三个列表框,每个列表框之间有两个左右箭头按钮,用于将第一个列表框项目移动到中间,中间回到第一个,等等。

sender我的函数通过和在语句中接受不同的按钮名称switch,我想选择要从哪些listBox选定项目发送以及它们将发送到哪里。如果这是有道理的。

底部的 while 循环将执行实际的移动,具体取决于为 "to" 和 "from" 设置的内容listBoxes

我的问题是如何在该函数的范围内引用语句listBoxes的每个案例中存在的三个名称?switch我知道像我所做的那样初始化new listBox是错误的,只会创建更多listBoxes的 . 也许对于这种情况,最简单的事情是while在每个语句中显式地放置循环case,但对于未来更复杂的场景,我仍然想知道这是如何完成的。

private void move(object sender, EventArgs e)
{
    Button thisButton = sender as Button;
    ListBox to = new ListBox();
    ListBox from = new ListBox();

    switch (thisButton.Name)
    {
        case "queueToProgressButton":
            to.Name = "queueListBox";
            from.Name = "progressListBox";
            break;
        case "progressToQueueButton":                    
            to.Name = "queueListBox";
            from.Name = "progressListBox";
            break;
        case "progressToCompletedButton":                    
            to.Name = "queueListBox";
            from.Name = "progressListBox";
            break;
        case "completedToProgressButton":                    
            to.Name = "queueListBox";
            from.Name = "progressListBox";
            break;

    }
    while (from.SelectedItems.Count > 0)
    {
        to.Items.Add(from.SelectedItem);
        from.Items.Remove(from.SelectedItem);
    }
}
4

1 回答 1

2

您应该使用对现有列表框的引用,而不是分配新列表框。此外,您发布的代码中的四个分支switch是相同的;我不认为那是你的本意。我根据我认为您在switch.

尝试这样的事情:

private void move(object sender, EventArgs e)
{
    Button thisButton = sender as Button;
    ListBox toListBox, fromListBox;

    switch (thisButton.Name)
    {
        case "queueToProgressButton":
            toListBox = progressListBox; // notice no "", but actual references
            fromListBox = queueListBox;
            break;
        case "progressToQueueButton":                    
            toListBox = queueListBox;
            fromListBox = progressListBox;
            break;
        case "progressToCompletedButton":                    
            toListBox = completedListBox;
            fromListBox = progressListBox;
            break;
        case "completedToProgressButton":                    
            toListBox = completedListBox;
            fromListBox = progressListBox;
            break;
        // Should add a default just in case neither 
        // toListBox or fromListBox is assigned here.
    }

    while (fromListBox.SelectedItems.Count > 0)
    {
        toListBox.Items.Add(fromListBox.SelectedItem);
        fromListBox.Items.Remove(fromListBox.SelectedItem);
    }
}
于 2012-02-13T01:44:01.797 回答