ComboBoxで名前を選択した時に値を取り出すには?

解決


ester  2005-06-10 17:42:07  No: 15504

以下のことはグローバルなTstringListを使わずに実現できるでしょうか?

var St:TstringList;
//---------------------------------------------
procedure TForm1.FormCreate(Sender: TObject);
var i:Integer;
begin
  St:=TstringList.create;
  St.CommaText:='東京=4513,横浜=8525,京都=2285,大阪=1515';
  for i:=0 to ST.Count-1 do ComboBox1.Items.Add(St.Names[i]);
end;
//---------------------------------------------
procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key=#13 then begin
    ShowMessage(St.Values[ComboBox1.Text]);
    St.free;
  end;
end;


deldel  2005-06-10 18:38:59  No: 15505

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.Items.Add('東京');
  ComboBox1.Items.Add('横浜');
  ComboBox1.Items.Add('京都');
  ComboBox1.Items.Add('大阪');
  ComboBox2.Items.Add('4513');
  ComboBox2.Items.Add('8525');
  ComboBox2.Items.Add('2285');
  ComboBox2.Items.Add('1515');
  ComboBox2.Hide;
end;

procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key=#13 then begin
    ShowMessage(ComboBox2.Items[ComboBox1.ItemIndex]);
  end;
end;


Basser  2005-06-10 19:10:20  No: 15506

値が整数値のようなので Obejctsプロパティで実現できます。

procedure TForm1.FormCreate(Sender: TObject);
var
  SL: TStringList;
  I : Integer;
begin
  SL:= TStringList.Create;
  try
    SL.CommaText:= '東京=4513,横浜=8525,京都=2285,大阪=1515';
    for I:= 0 to SL.Count - 1 do
      ComboBox1.Items.AddObject(
        SL.Names[I], TObject(StrToIntDef(SL.Values[SL.Names[I]], 0))
      );
  finally
    SL.Free;
  end;
end;

procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
begin
  if (Key = #13) then
    ShowMessage(IntToStr(Integer(ComboBox1.Items.Objects[ComboBox1.ItemIndex])));
end;


ester  2005-06-10 20:46:55  No: 15507

ComboBoxで名前を選択した時に値を取り出すことは頻繁に使うのですが、
いつもグローバルのStringListが目障りでした。
deldel様、Basser様、
なるほど!の斬新なアイデアをありがとうございました。


※返信する前に利用規約をご確認ください。

※Google reCAPTCHA認証からCloudflare Turnstile認証へ変更しました。






  このエントリーをはてなブックマークに追加