How to MultiSelect in the Delphi DBGrid

Delphi's DBGrid is one of the most widely used DB-aware components in database related applications. Its main purpose is to enable your application's users to manipulate records from a dataset in a tabular grid.

One of the lesser known features of the DBGrid component is that it can be set to allow multiple row selection. What this means is that your users can have the ability to select multiple records (rows) from the dataset connected to the grid.

Allowing Multiple Selections
To enable multiple selection, you only need to set the dgMultiSelect element to "True" in the Options property. When dgMultiSelect is "True," users can select multiple rows in a grid using the following techniques:

Ctrl + Mouse click
Shift + Arrow keys
The selected rows/records are represented as bookmarks and stored in the grid's SelectedRows property.

Note that SelectedRows is only useful when the Options property is set to "True" for both dgMultiSelect and dgRowSelect. On the other hand, when using dgRowSelect (when individual cells cannot be selected) the user won't be able to edit records directly through the grid and, and dgEditing is automatically set to "False."

The SelectedRows property is an object of type TBookmarkList. We can use the SelectedRows property to, for example:

Get the number of rows selected
Clear the selection (unselect)
Delete all the selected records
Check whether a particular record is selected
To set dgMultiSelect to "True," you can either use the Object Inspector at design time or use a command like this at runtime:

DBGrid1.Options:= DBGrid1.Options + [dgMultiSelect];
dgMultiSelect Example
A good situation in which to use dgMultiSelect might be when you need an option to select random records or if you need the sum of the values of the selected fields.

The example below uses ADO components (AdoQuery connected to ADOConnection and DBGrid connected to AdoQuery over DataSource) to display the records from a database table in a DBGrid component.

The code uses multiple selection to get the sum of the values in the "Size" field. Use this sample code if you want to select the entire DBGrid:

procedure TForm1.btnDoSumClick(Sender: TObject);
var
i: Integer;
sum : Single;
begin
if DBGrid1.SelectedRows.Count > 0 then
begin
sum := 0;
with DBGrid1.DataSource.DataSet do
begin
for i := 0 to DBGrid1.SelectedRows.Count-1 do
begin
GotoBookmark(Pointer(DBGrid1.SelectedRows.Items[i]));
sum:= sum + AdoQuery1.FieldByName('Size').AsFloat;
end;
end;
edSizeSum.Text := FloatToStr(sum);
end
end;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值