Author: William Gerbert
A combobox in a cell of a stringgrid
Answer:
Here's another great trick by programmer illusionists. What appears as embedded
comboboxes within a stringgrid is actually just a combobox floating above the
stringgrid, and it just so happens to be the exact same size as the stringgrid cell
underneath it.
Here's the basics:
1 procedure TfrmMain.FormCreate(Sender: TObject);
2 begin
3 StringGrid1.DefaultRowHeight := ComboBox1.Height;
4 end;
5
6 procedure TfrmMain.StringGrid1DrawCell(Sender: TObject; Col, Row:
7 Integer; Rect: TRect; State: TGridDrawState);
8 var
9 R: TRect;
10 begin
11 if (Col >= StringGrid1.FixedCols) and
12 (Row >= StringGrid1.FixedRows) and
13 (gdFocused in State) then
14 with ComboBox1 do
15 begin
16 BringToFront;
17 CopyRect(R, Rect);
18 R.TopLeft := frmMain.ScreenToClient(
19 StringGrid1.ClientToScreen(R.TopLeft));
20 R.BottomRight := frmMain.ScreenToClient(
21 StringGrid1.ClientToScreen(R.BottomRight));
22 SetBounds(R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top);
23 end;
24 end;
25
26 procedure TfrmMain.StringGrid1TopLeftChanged(Sender: TObject);
27 var
28 R: TRect;
29 begin
30 with StringGrid1 do
31 CopyRect(R, CellRect(Col, Row));
32
33 with ComboBox1 do
34 begin
35 Visible := False;
36 R.TopLeft := frmMain.ScreenToClient(
37 StringGrid1.ClientToScreen(R.TopLeft));
38 R.BottomRight := frmMain.ScreenToClient(
39 StringGrid1.ClientToScreen(R.BottomRight));
40 SetBounds(R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top);
41 end;
42
43 with StringGrid1 do
44 if (TopRow <= Row) and (TopRow + VisibleRowCount > Row) then
45 ComboBox1.Show;
46 end;
47
48 procedure TfrmMain.ComboBox1Change(Sender: TObject);
49 begin
50 with StringGrid1 do
51 Cells[Col, Row] := ComboBox1.Text;
52 end;
In essence, the main routine here is the stringgrid's OnDrawCell event handler. Of
course, I also set the stringgrid's DefaultRowHeight property to be the same height
as the combobox. In addition, the stringgrid's OnTopLeftChanged event handler is
used to hide the combobox when the user scrolls out of view. Also, when the user
selects an item from the combobox, simply place the text in the current Col/Row.
You can also do a couple other little tricks such as setting the stringgrid's Objects[] property to point to the combobox, as well as possibly setting the combobox's Parent property to point to the stringgrid. However, I've had problems with the Parent approach -- namely, that of dropping down the listbox associated with the combobox.
|