一次测试多个TComboBox值

时间:2011-03-27 14:47:48

标签: delphi testing combobox

我是德尔福的菜鸟,但请帮助。

我在表单上有7个TComboBox。使用名为Numbers的同一个表中的SQL查询将它们的值分配给它们。

procedure TForm3.Button4Click(Sender: TObject);
begin

Q2.Close;
Q2.SQL.Clear;
Q2.SQL.Add ('Select num');
Q2.SQL.Add ('FROM numbers.dbf');
Q2.RequestLive := true;
Q2.Open;
cb1.Items.Add(q2.FieldByName('num').value);
cb1.Text:= '? ? ?';
cb2.Items.Add(q2.FieldByName('num').value);
cb2.Text:= '? ? ?';
...
...
...
end;

其中cb1,cb2 ....是TComboBoxes。

当我点击它们时,我正试图让它们相互测试它们的值(所有值都是文本)。具体来说,如果您从下拉列表中选择cb1 = 1,那么如果您选择cb2 = 1 ...等并且您指定了相同的数字,它应该会给您一条错误消息

MessageDlg('Check Values: CB 1 and CB 2: Same Values Entered.',mtError, mbOKCancel, 0);

你推荐我使用哪种方法,我现在已经打了两天了。

提前致谢!

2 个答案:

答案 0 :(得分:4)

使用七个组合框(Style := csDropDownList)创建一个新表单。然后,创建一个

var
  combos: array[1..7] of TComboBox;

并启动它:

procedure TForm1.FormCreate(Sender: TObject);
begin
  combos[1] := ComboBox1;
  combos[2] := ComboBox2;
  combos[3] := ComboBox3;
  combos[4] := ComboBox4;
  combos[5] := ComboBox5;
  combos[6] := ComboBox6;
  combos[7] := ComboBox7;
end;

然后你可以做

procedure TForm1.VerifyUniqueness(Sender: TObject);
begin
  if LongBool(TComboBox(Sender).Perform(CB_GETDROPPEDSTATE, 0, 0)) then
    Exit;
  for i := low(combos) to high(combos) do
    if (Sender <> combos[i]) and SameStr(TComboBox(Sender).Text, combos[i].Text) then
      raise Exception.CreateFmt('The fields %s and %s have the same value.', [TComboBox(Sender).Name, combos[i].Name]);
end;

并将VerifyUniqueness分配给每个组合框的OnChange事件。另外,你需要

procedure TForm1.ComboBoxesKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_RETURN then VerifyUniquness(Sender);
end;

答案 1 :(得分:1)

每次组合框的值更改时进行验证确实会导致一些小的不便。如果你想交换两个组合框的值,你必须以迂回的方式这样做。

  • 将第一个设置为临时第三个值。
  • 将秒设置为原始的第一个值。
  • 将第一个设置为原始第二个值。

以下代码提供了在任何时间点验证所有组合框的方法。例如。当用户单击“确定”按钮时。当然,每次值更改时,您仍然可以调用该方法。

代码也使用了一组组合框和Andreas Rejbrand's answer一样,所以我不会重复代码的那一部分。

procedure ValidateComboBoxes;
var
  LCombValues: TStrings;
  I: Integer;
  LDuplicateIndex: Integer;
begin
  LComboValues := TStringList.Create;
  try
    for I := Low(FCombos) to High(FCombos) do
    begin
      LDuplicateIndex := LComboValues.IndexOf(FCombos[I].Text);
      if (LDuplicateIndex >= 0) then
      begin
        raise Exception.Create('The value: ['+FCombos[I].Text+
          '] has been duplicated in the following Combo Boxes: ['+FCombos[I].Name+
          '] and ['+TComboBox(LComboValues.Objects[LDuplicateIndex]).Name+']');
      end;
      LComboValues.AddObject(FCombos[I].Text, FCombos[I]);
    end;
  finally
    LComboValues.Destroy;
  end;
end;