web-dev-qa-db-ja.com

すべてのリストボックスアイテムを削除する方法は?

2つのRadioButton(WeightとHeight)を作成しました。 2つのカテゴリを切り替えます。しかし、それらは同じListBoxコントローラー(listBox1とlistBox2)を共有します。

すべてのリストボックス項目をより簡単にクリアする良い方法はありますか? ListBoxのremoveAll()が見つかりませんでした。ここに投稿した複雑な複数行スタイルは好きではありません。

private void Weight_Click(object sender, RoutedEventArgs e)
    {
        // switch between the radioButton "Weith" and "Height"
        // Clear all the items first
        listBox1.Items.Remove("foot"); 
        listBox1.Items.Remove("inch");
        listBox1.Items.Remove("meter");
        listBox2.Items.Remove("foot");
        listBox2.Items.Remove("inch");
        listBox2.Items.Remove("meter");

        // Add source units items for listBox1
        listBox1.Items.Add("kilogram");
        listBox1.Items.Add("pound");

        // Add target units items for listBox2
        listBox2.Items.Add("kilogram");
        listBox2.Items.Add("pound");
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        // switch between the radioButton "Weith" and "Height"
        // Clear all the items first
        listBox1.Items.Remove("kilogram");
        listBox1.Items.Remove("pound");
        listBox2.Items.Remove("kilogram");
        listBox2.Items.Remove("pound");

        // Add source units items for listBox1
        listBox1.Items.Add("foot");
        listBox1.Items.Add("inch");
        listBox1.Items.Add("meter");

        // Add target units items for listBox2
        listBox2.Items.Add("foot");
        listBox2.Items.Add("inch");
        listBox2.Items.Add("meter");
    }
31
Nano HE

winformおよびWebformの方法と同じではありませんか?

listBox1.Items.Clear();
78
balexandre

各リストボックスに同じ要素を追加しているように見えるので、実際にリストボックスをデータソースにバインドする方が良いと思います。簡単な例は次のようになります。

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }
8
Matt Dearing

.csファイルに次のコードを記述します。

ListBox.Items.Clear();

2
Pulkit

Clear()メソッドを使用できるはずです。

2
user1017477
while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}
2
  • VB ListBox2.DataSource =なし
  • C#ListBox2.DataSource = null;
0
Paulos02

私はこの方法で作成し、適切に作業しました:

if (listview1.Items.Count > 0)
        {
            for (int a = listview1.Items.Count -1; a > 0 ; a--)
            {
                listview1.Items.RemoveAt(a);
            }
                listview1.Refresh();

        }

説明:「Clear()」を使用するとアイテムのみが消去され、オブジェクトからは削除されません。RemoveAt()を使用して開始位置のアイテムが削除されると、他のアイテムが再割り当てされます。 [0]新しい内部イベントをトリガーする]ので、エンディングから他の位置に影響を与えず、スタックの動作に影響を与えないため、すべてのアイテムをスタックしてオブジェクトをリセットできます。

0
Bruno