1

私は用語を混乱させるかもしれませんが、私がやろうとしていることは次のとおりです。

選択したアイテムを別のアイテムに移動する移動機能がありますlistBox。3 つのリスト ボックスがあり、それぞれの間に 2 つの右矢印ボタンと左矢印ボタンがあり、最初のリスト ボックス項目を中央に移動したり、中央を最初のリスト ボックス項目に戻したりすることができます。

sender私の関数は、ステートメントを介してさまざまなボタン名を受け入れます。選択したアイテムの送信元と送信先をswitch選択したいと思います。listBoxそれが理にかなっていれば。

一番下の while ループは、「to」と「from」の設定に応じて、実際の移動を実行しlistBoxesます。

私の質問は、この関数のスコープ内で、ステートメントlistBoxesの各ケースに存在する 3 つの名前をどのように参照できるかということです。switch私が行ったように a を初期化するのnew listBoxは間違っていることを知っており、さらに を作成しますlistBoxeswhileこの場合、各ステートメントにループを明示的に配置するのが最も簡単な方法かもしれませんが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

新しいリスト ボックスを割り当てるのではなく、既存のリスト ボックスへの参照を使用する必要があります。また、あなたの 4 つのブランチは、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 に答える