ListBoxの使用方法(2)

 

複数行を選択
重複を避ける
便利なメソッド
重複を避ける 1/2
1/2
追加する前にIndexOfメソッドを使用します。
このメソッドは、文字列リストに一致する文字列がない場合、-1 を返します。
-1 が返された場合に、文字列リストに追加するように記述します。
[選択]ボタンのOnClickイベントで次のように1行追加します。
procedure TForm1.Button2Click(Sender: TObject);
var
  str : string;
  i   : integer;
begin
  if  ListBox1.SelCount > 0  then
    for  i:=  0  to  ListBox1.Items.Count - 1  do
    begin
      if  ListBox1.Selected[i] =  True  then
      begin
        //選択している文字列を取得
        str := ListBox1.Items[i];
        //取得した文字列を追加
        if  ListBox2.Items.IndexOf(str) = -1  then   //この行を追加
          ListBox2.Items.Add(str);
      end;
    end;
end;

 

1/2