C# listBox 他のlistBoxへの移動

スポンサーリンク

今日もC#。 仕事中はずーっと社内ツール開発の為に時間を使っています。 本当はサーバ保守。でも最近故障も問合せも無いのでセコセコC#してますw

今日は、2つのリストボックス間でのItemの移動。 意外と多く目にするコントロールだ。

 

今日は上記のうち「>」「<」「↑」「↓」のボタンの設定方法をご紹介します。

「>」:listBox1で選択したItemをlistBox2に移動し、移動後listBox1から削除。

//【ボタン1】右へ追加ボタン
private void button1_Click(object sender, EventArgs e)
{
//現在選択されているItemのインデックス取得
int Index = this.listBox1.SelectedIndex;
//リストボックスで選択されているものがある場合(無い場合Indexは「-1」)
if (Index >= 0)
{
//隣のリストボックスに現在選択中のItemを追加
this.listBox2.Items.Add(this.listBox1.SelectedItem);
//現在のリストボックスから選択済みItemを削除
this.listBox1.Items.Remove(this.listBox1.SelectedItem);
//選択済みアイテムがリストItemsの値と一緒の場合、
if (this.listBox1.Items.Count == Index)
{
//Indexを1下げる
this.listBox1.SelectedIndex = Index - 1;
}
//それ以外の場合
else
{
//インデックス(選択済み行)は変わらず
this.listBox1.SelectedIndex = Index;
}
}
}

 

「>」:listBox2で選択したItemをlistBox1に移動し、移動後listBox2から削除。

//【ボタン2】左へ追加ボタン
private void button2_Click(object sender, EventArgs e)
{
int Index = this.listBox2.SelectedIndex;
if (Index >= 0)
{
//隣のリストボックスに現在選択中のItemを追加
this.listBox1.Items.Add(this.listBox2.SelectedItem);
//現在のリストボックスから選択済みItemを削除
this.listBox2.Items.Remove(this.listBox2.SelectedItem);
//選択済みアイテムがリストItemsの値と一緒の場合、
if (this.listBox2.Items.Count == Index)
{
//Indexを1下げる
this.listBox2.SelectedIndex = Index - 1;
}
//それ以外の場合
else
{
//インデックス(選択済み行)は変わらず
this.listBox1.SelectedIndex = Index;
}
}
}

 

「↑」:listBox2で選択されたアイテムを一つ上に移動する。

//【ボタン6】並び替え(上へ)
private void button6_Click(object sender, EventArgs e)
{
//リストボックスにて選択されたIndex
int Index = this.listBox2.SelectedIndex;
//リストボックスにて選択されたItem
object selected = this.listBox2.SelectedItem; 

if (Index > 0)
{
//現在選択済みのItemを削除
this.listBox2.Items.Remove(selected);
//選択済みのItemの「Index」から「-1」したIndexにItemをInsert
this.listBox2.Items.Insert(Index - 1, selected);
//選択済みアイテムは変わらず。
this.listBox2.SelectedItem = selected;
}
}

 

 

「↓」:listBox2で選択されたアイテムを一つ下に移動する。

//【ボタン7】並び替え(下へ)
private void button7_Click(object sender, EventArgs e)
{
//リストボックス内のItemの数を「items」として取得
int items = this.listBox2.Items.Count;
//現在選択中のItemのIndexを取得
int Index = this.listBox2.SelectedIndex;
//リストボックスにて選択されたItem
object selected = this.listBox2.SelectedItem; 

//もし現在選択済みItemのIndexが、Items数よりも小さい場合
if (Index < items - 1)
{
//現在選択済みのItemを削除
this.listBox2.Items.Remove(selected);
//選択済みのItemの「Index」から「+1」したIndexにItemをInsert
this.listBox2.Items.Insert(Index + 1, selected);
//選択済みアイテムは変わらず。
this.listBox2.SelectedItem = selected;
}
}

 

C#
スポンサーリンク
スポンサーリンク
trippyboyをフォローする
TrippyBoyの愉快な日々

コメント

  1. trippyboy より:

    上へ下への中、listbox内での選択が行なわれているときはという条件が無いと、選択が無いときにエラーになる。

    if(this.listBox2.SelectedItem != null)
    {
    }

    で両者とも調整した。

タイトルとURLをコピーしました