Delphi filling combobox items from SQL database [closed]

為{幸葍}努か 提交于 2019-12-10 16:59:02

问题


I want to fill my combobox with data from a SQL database but it doesn't work. My query has a connection to the database, query SQL property field is select * from provider_table

Query1.SQL.Clear;
Query1.SQL.Add('select name from provider_table where region_code = '+quotedstr('eng')');
Query1.Open;

while NOT Query1.Eof do begin
   ComboBox1.Items.Add(Query1['name']);
   Query1.Next;
end;

Does anyone have an idea? Thanks for the answers!


回答1:


Is this what you are looking for?

procedure SelCombo(sql:ansiString;Q:TSQLQuery; var Combo:TComboBox);
var i: integer;
begin
  Q.Close;
  Q.SQL.Text:='';
  Q.Open(sql);
  Combo.Text:='';
  while not Q.Eof do begin
    Combo.Items.Add(Q.Fields.Fields[0].AsString);
    Q.Next;
  end;
  Q.Close;
end;



回答2:


This isn't so much about the combo-box as whether you're getting anything returned from your query. The first thing to do is ensure that the query is working. I'd first put a TMemo or TList on the form and mess with the query until it's returning the data you're expecting.

Alternatively, drop a DB-aware component on the form and hook it to the TSqlQuery component to verify you're getting a non-empty result set.

"Select * from provider_table" may well be returning items, but the query in the example is far more specific and it may not be returning anything.

Once you've verified you're getting a non-empty result set, THEN fill up the combo-box.

Ensure that its style property is set to "Dropdown List" so the user can only select from the returned items.

Also, FWIW, lists of items placed into combo-boxes like this from database queries are, more often than not, lists of foreign keys from another table than what you're dealing with. So a DB-combobox that allows foreign-key selection to fill it up is a much better way to go than the approach you're using. You set a couple of properties in the Object Inspector and it fills itself when the form loads.

It's also common in such situations that the string displayed in the combo-box is also NOT the value used as the key in the table or as the foreign-key value. Instead, an index (number) might be used. This requires a lookup property where the selected item is mapped to another value that the database tables use. (Not all combo-boxes are the same when it comes to DB uses!)



来源:https://stackoverflow.com/questions/24597682/delphi-filling-combobox-items-from-sql-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!