如何获得TDBLookupComboBox的价值?

时间:2015-03-08 06:02:42

标签: delphi

我的数据库Tb_barangTb_jenis上有表格。 Tb_jenis以下列kd_jenis(主键)和jenis。我使用TDBLookupComboBox来显示Tb_jenis表中的项目。共有6件商品(Mie,Susu等)。我想保存选为kd_jenis而不是jenis的项目。

如何将表格中的jenis保存到kd_jenis?

Sample data: Tb_jenis
jenis   kd_jenis
Mie     J1
Susu    J2

这是我尝试过的代码。

if (kd.Text='') or (jenis.Text='Pilih')  then
  ShowMessage('Data Tidak Lengkap, Silakkan Dilengkapi !')
else
begin
  with dm.Qbarang do 
  begin 
    sql.Clear;
    SQL.Add('select * from Tb_barang where kd_barang='+quotedstr(kd.text)+'');
    open;
  end;
  if DM.Qbarang.Recordset.RecordCount > 0 then
    ShowMessage('Data Sudah Ada, Silakkan Isi Yang Lain!')
  else
  begin
    try
      DM.koneksi.BeginTrans;
      with DM.QU do
      begin
        close;
        SQL.Clear;
        SQL.Add('insert into Tb_barang values('+QuotedStr(kd.Text)+','
                +QuotedStr(jenis.Text)+')');
        ExecSQL;
      end;
      DM.koneksi.CommitTrans;
      ShowMessage('Data Berhasil Disimpan');
    except 
      DM.Qbarang.Close;
      DM.Qbarang.Open;
      FormShow(sender);
    end;
  end;
end;

4 个答案:

答案 0 :(得分:0)

据我所知,你想从DBLookupComboBox获取表的键值。 所以它是DBLookupComboBox ListField和KeyField中的两个重要属性 如果你正确设置它们对于示例KeyField设置为kd_jenis并列出字段设置为jenis,那么你将看到列表中的Jenis,你可以访问DBLookupCombobox.text中的jenis,你也可以通过DBLookupCombobox访问KeyField(在本例中为kd_jenis)。 KEYVALUE

答案 1 :(得分:0)

如果您遇到DBLookupComboBox问题,可以使用普通的组合框,并像示例here一样填充它。

答案 2 :(得分:0)

你应该休息这一步。

  1. 将TADOConnection放入表单以连接数据库。
  2. 构建连接到数据库的连接字符串。
  3. 在表单中添加ADO表。
  4. 将Connection属性设置为AdoConnection1(ADOCOnnection的默认名称)。
  5. 在ADOTable上打开表名属性并选择一个数据库表,然后将活动属性设置为true。
  6. 将数据源添加到表单并将数据集属性设置为ADOTable1(默认名称为ADOTable)
  7. 将DBLookupCombobox添加到表单并将ListSource设置为DataSource1(数据源的默认名称)
  8. 打开ListField属性并选择要在Combobox中显示的女巫字段。
  9. 打开keyField属性,选择女巫字段为关键字段。
  10. 上述所有步骤均应在设计时完成。为了测试你的应用程序添加到表单上的编辑框edit1和edit2然后写一个小代码为OnCloseUp Evwnt的DBLookupCombobox像这样

    Edit1.Text:=DBLookUpCombobox1.KeyValue; Edit2.Text:=DBLookupCombobox1.Text;

答案 3 :(得分:0)

有人在您的DBLookupComboBox中选择某些内容后...移动到表格的光标。

您可以直接访问该值:

jenis.ListSource.DataSet.FieldByName('kd_jenis').AsString

这假设jenis是TDBLookupComboBox。 ListSource.DataSet指向Tb_jenis。

正如Craig所说......你的代码中有一个严重的错误......你需要一个例外的RollbackTrans ......其他明智的你永远不会释放锁......

  DM.koneksi.CommitTrans;
  ShowMessage('Data Berhasil Disimpan');
except
  DM.koneksi.RollbackTrans; 
  DM.Qbarang.Close;
  DM.Qbarang.Open;
  FormShow(sender);
end;

我这样做......如果我需要保证保存信息并在失败时回滚。

procedure TForm8.SaveData;
begin
  Assert(not ADOQuery1.Connection.InTransaction, 'Code problem-We should not be in a Transaction');
  ADOQuery1.Connection.BeginTrans;
  try
    ADOQuery1.ExecSQL;
    ADOQuery1.Connection.CommitTrans;        
  finally
    if ADOQuery1.Connection.InTransaction then
    begin
      {If you are here...your in an ErrorState...and didn't Commit your Transaction}
      ADOQuery1.Connection.RollbackTrans;
      HandleError(ADOQuery1);
    end;
  end;
end;