Delphi DBGrid usage Overview

Source: Internet
Author: User
Tags textout

In Delphi, the grid control (DBGrid) is often used to display data. The grid control only provides the color attribute of each row, however, in practical applications, we often want it to display different colors based on the values of one item in a row, or even display images in the unit table items in the grid, the following is a simple example to show you how to do this.

For example, if there is a refund in spring, it is marked in red, and if there is a refund in autumn, it is marked in yellow.

The DBGrid self-painting function can easily meet such requirements. You can handle the ondrawcolumncell event of DBGrid to achieve special effects. To determine whether the disconnection record meets the requirements, you can use the datalink attribute of DBGrid to obtain data. However, the datalink attribute of DBGrid is a protected member and must be called in the subclass of tcustomdbgrid.

Type
Tmycustomdbgrid = Class (tcustomdbgrid );

Procedure tform1.dbgrid1drawcolumncell (Sender: tobject; const rect: trect;
Datacol: integer; column: tcolumn; State: tgriddrawstate );
VaR
Scjts, sqjts: string;
Begin
With tmycustomerdbgrid (sender) Do
Begin
Cjts: = datalink. Fields [5]. asstring;
Sqjts: = datalink. Fields [9]. asstring;
If scjts <> ''then // number of books returned in spring> 0 is displayed in red
Canvas. Brush. Color: = clred
Else
If sqjts <> ''then // The number of books returned in the Fall> 0 is displayed in yellow
Canvas. Brush. Color: = clyellow
Else
Canvas. Brush. Color: = clwhite;
Canvas. Font. Color: = clblack;
Canvas. fillrect (rect );
Canvas. textout (rect. Left + 4, rect. Top + 4, column. Field. asstring );
End;
End;

This method can extend a variety of modification methods for other controls. For example, you can use different colors based on data item values and display different colors based on record numbers. In short, the flexible application of canvas, rect, bitmap and other objects, can be decorated with a variety of mesh colorful.

How can we get the DBGrid row number instead of the dataset row number?
Edit1.text: = inttostr (tdrawgrid (dbgrid1). Row );

In database programming in Delphi, DBGrid is one of the main means of displaying data. However, the default appearance of DBGrid is monotonous and lacks creativity. In fact, we can program our programs to beautify the appearance of DBGrid. Through programming, we can change the foreground color and background color of the DBGrid header, grid, and grid lines, as well as the size and style of related fonts.
The following example demonstrates how to set the attributes of DBGrid so that the tables displayed by Delphi are as beautiful as those displayed on the webpage.
Run the sample program:
Place dbgrid1, query1, and performance1 database components on form1 and set relevant attributes so that dbgrid1 can display table data. Then, type the following code in the ondrawcolumncell event of dbgrid1, and run the program to see the magic result. This code is successfully debugged in Windows 98 and Delphi5.0 environments.
Procedure tmainform. dbgrid1drawcolumncell (Sender: tobject;
Const rect: trect; datacol: integer; column: tcolumn; State: tgriddrawstate );
VaR I: integer;
Begin
If gdselected in State then exit;
// Define the font and background color of the header:
For I: = 0 to (sender as TDBGrid). Columns. Count-1 do
Begin
(Sender as TDBGrid). Columns [I]. Title. Font. Name: = 'body'; // font
(Sender as TDBGrid). Columns [I]. Title. Font. Size: = 9; // font size
(Sender as TDBGrid). Columns [I]. Title. Font. Color: = $ 000000ff; // font color (red)
(Sender as TDBGrid). Columns [I]. Title. Color: = $0000ff00; // background color (green)
End;
// Change the grid background color on the line:
If query1.recno mod 2 = 0 then
(Sender as TDBGrid). Canvas. Brush. Color: = clinfobk // defines the background color.
Else
(Sender as TDBGrid). Canvas. Brush. Color: = RGB (191,255,223); // defines the background color.
// Define the gridline color:
Dbgrid1.defadrawcolumncell (rect, datacol, column, State );
With (sender as TDBGrid). Canvas do // draw the cell border
Begin
Pen. Color: = $00ff0000; // defines the paint brush color (blue)
MoveTo (rect. Left, rect. Bottom); // specifies the paint brush.
Lineto (rect. Right, rect. Bottom); // draw a blue horizontal line
Pen. Color: = $0000ff00; // defines the paint color (green)
MoveTo (rect. Right, rect. Top); // specifies the paint brush.
Lineto (rect. Right, rect. Bottom); // draw a green vertical line
End;
End;

--- Change the color of the DBGrid mesh through the line

Place dbgrid1, query1, and performance1 database components on form1 and set relevant attributes so that dbgrid1 can display table data. Then, type the following code in the ondrawcolumncell event of dbgrid1, and then run the program

Code:
Procedure tform1.dbgrid1drawcolumncell (Sender: tobject; const rect: trect;
Datacol: integer; column: tcolumn; State: tgriddrawstate );

VaR I: integer;
Begin
If gdselected in State then exit; // you can change the grid background color in the following way:
If adoquery1.recno mod 2 = 0 then
(Sender as TDBGrid). Canvas. Brush. Color: = clinfobk // defines the background color.
Else
(Sender as TDBGrid). Canvas. Brush. Color: = RGB (191,255,223); // defines the background color.

// Define the gridline color:
Dbgrid1.defadrawcolumncell (rect, datacol, column, State );
With (sender as TDBGrid). Canvas do // draw the cell border
Begin
Pen. Color: = $00ff0000; // defines the paint brush color (blue)
MoveTo (rect. Left, rect. Bottom); // specifies the paint brush.
Lineto (rect. Right, rect. Bottom); // draw a blue horizontal line
Pen. Color: = clbtnface; // defines the paint brush color (blue)
MoveTo (rect. Right, rect. Top); // specifies the paint brush.
Lineto (rect. Right, rect. Bottom); // green
End;
End;

Table1 In BDE fails to pass, and the color does not change across rows.

You can insert other visual components into DBGrid of Delphi. Delphi provides powerful DBGrid components to facilitate database application design. However, if we only use the DBGrid component, each acquired focus (GRID) is a simple text editing box, which is inconvenient for users to input data. Delphi also provides some other data components to facilitate user input, such as dbcombobox and dbcheckbox, but these components do not have the powerful functions of DBGrid. Can Delphi make the focus grid in DBGrid as Visual FoxPro can be other visual data components to facilitate users? In fact, we can achieve this by inserting other visual components in DBGrid.

Delphi's internal mechanism for DBGrid processing is to move a component, dbedit, to the floating point of the grid. The mesh of the data you enter is actually a floating dbedit component, and the rest of the areas where the focus is not obtained are just images. Therefore, inserting other visual components in DBGrid is to move a visible component on the grid. Therefore, any component, from a simple dbcheckbox to a complex dialog box, can be inserted in DBGrid. The following describes how to insert the dbcombobox component in DBGrid. Other components can be inserted in the same way.

1. Create a new project in Delphi 4.0.

2. Drag the datasource, table, DBGrid, and dbcombobox components on the Data Access Component board to form1.

3. Set the attributes of each component as follows:

Rcf1 Object Property setting
Form1 caption 'example of inserting the spinedit component in DBGrid'
Performance1 dataset Table1
Table1 databasename dbdemos
Tablename 'Teacher. dbf'
Active true
Dbgrid1 datasource performance1
Dbcombobox1 datafield sex
Datasource performance1
Visible false
Strings items. 'male' | 'female'

Note: Here I use teacher. DBF, which reflects the gender of the faculty and staff. It can only be "male" or "female ".

4. The drawdatacell event is used to draw cells. When the fields corresponding to the obtained focus mesh are consistent with those corresponding to the combo box, move the combo box to the mesh with the obtained focus, and make the combo box visible, this allows you to display dbcombobox in a column specified by DBGrid. The ondrawdatacell event of dbgrid1 is set as follows:

Procedure tform1.dbgrid1drawdatacell (Sender: tobject; const rect: trect; field: tfield; State: tgriddrawstate );
Begin
If (gdfocused in State) then
Begin
If (field. fieldname = dbcombobox1.datafield) then
Begin
Dbcombobox1.left: = rect. Left + dbgrid1.left;
Dbcombobox1.top: = rect. Top + dbgrid1.top;
Dbcombobox1.width: = rect. Right-rect. Left;
Dbcombobox1.height: = rect. Bottom-rect. Top;
Dbcombobox1.visible: = true;
End;
End;
End;

5. dbcombobox is not displayed when the cell specified by DBGrid is not focused. The oncolexit event for dbgrid1 is set as follows:
Procedure tform1.dbgrid1colexit (Sender: tobject );
Begin
If dbgrid1.selectedfield. fieldname = dbcombobox1.datafield then
Begin
Dbcombobox1.visible: = false;
End;
End;

6. When DBGrid specifies that the column gets the focus, the drawdatacell event only draws cells and displays dbcombobox. However, dbcombobox does not get the focus, and the data input is still performed on cells. In the keypress event of dbgrid1, the Windows API function sendmessage is called to transmit data input to dbcombobox, so as to input data on dbcombobox. Therefore, you must set the keypress event as follows:

Procedure tform1.dbgrid1keypress (Sender: tobject; var key: Char );
Begin
If (Key <> CHR (9) then
Begin
If (dbgrid1.selectedfield. fieldname = dbcombobox1.datafield) then
Begin
Dbcombobox1.setfocus;
Sendmessage (dbcombobox1.handle, wm_char, word (key), 0 );
End;
End;
End;

The program is successfully debugged in Windows 98 and Delphi 4.015. I hope this article will help you develop database applications more conveniently and quickly.

Lock the column on the left of DBGrid. When using delphi3 for database programming, I hope that the DBGrid component can display data like the Foxpro browse command, the specified columns on the left are locked and do not scroll. How can this problem be implemented?

We know that Delphi's tstringgrid has a property fixedcols to specify columns that do not scroll. Although TDBGrid cannot directly use this attribute, you can use this feature by force type conversion because both classes are from the tcustomgrid class. The following uses demos \ dB \ ctrlgrid of Delphi 3.0 as an example to describe the specific usage. Add the following line to the tfmctrlgrid. formshow process in this example:

Tstringgrid (dbgrid1). fixedcols: = 2;

Run this program. When the left and right columns are moved, the symbol column is not moved. In addition to this method, you can also use the following method: First add

Type tmygrid = Class (TDBGrid) end;

Then, add:

Tmygrid (dbgrid1). fixedcols: = 2;

The two are slightly different in form, but they are essentially the same. Here we set fixedcols to 2, because there is an indicator column at the far left of the DBGrid component, if you set the options attribute of DBGrid to false, set fixedcols to 1.

You can change the color of a grid or text in the drawdatacell event of the DBGrid component based on the condition of the data.
For example:

Ondrawdatacell (...)
Begin
With TDBGrid (sender) Do
Begin
If (condition) then
Canvas. textout (rect. Left + 4
Rect. Top + 2

'Text to be displayed, such as table information ');
End;

However, you will see how the data displayed by DBGrid overlaps with the data displayed by textout.
Solution:
In the ongettext event where you do not want to display data, set the field added to the query element to false (right-click the component and choose add fields;

Procedure tform1.query1detail1gettext (Sender: tfield; var text: string;
Displaytext: Boolean );
Begin
// Determine whether to display the obtained data when DBGrid learns the table data. False-> Do Not Display
// Avoid overlapping texts with textout.
Displaytext: = false;
End;
End;

If you use Delphi 3 to process a field, for example, when the value of a field in the table is smaller than 0, the other values are black characters.
In DBGrid. ondrawcolumncell:

Begin
If tablefield. asinteger <0 then
DBGrid. Canvas. Font. Color: = clred
Else
DBGrid. Canvas. Font. Color: = clblack;
DBGrid. defaultdrawcolumncell (...);
End;

In this way, the specified field format still takes effect without rewriting.

In practice, the Data Grid Control (TDBGrid) in Delphi plays an important role in displaying and editing a large amount of data in the database. However, while using the Data Grid Control, it is often because the large amount of data in the table is not easy to distinguish, and the operator is dazzled. How can we improve the ease of use of grid controls and overcome this deficiency? This article proposes a solution from the perspective of changing the color configuration of the Data Grid.

The following describes how to implement the six special effects of the Data Grid Control.

1. Vertical zebra effect: the odd series and even columns in the grid are displayed in different colors to differentiate adjacent data columns.
File: // write the following code in the drawcolumncell event of DBGrid:

Case datacol mod 2 = 0
True: dbgrid1.canvas. Brush. Color: = clblue; file: // blue for even Columns
False: dbgrid1.canvas. Brush. Color: = claqua; file: // light green for odd series
End;
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );

2. Vertical zebra crossings, and the current cell effect highlighted in red: to highlight the selected fields.

File: // modify the above Code:
Case datacol mod 2 = 0
True: dbgrid1.canvas. Brush. Color: = clblue; file: // blue for even Columns
False: dbgrid1.canvas. Brush. Color: = claqua; file: // light green for odd series
End;
If (State = [gdselected]) or (State = [gdselectedgdfocused]) then
If not dbgrid1.selectedrows. currentrowselected then
Dbgrid1.canvas. Brush. Color: = clred; file: // the currently selected cells are displayed in red.
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );

The above two methods highlight the Column Display Effect.

3. Highlight the selected row in red in the data grid.
Set the dgrowselect attribute in the options attribute of the DBGrid control to true, and the color attribute to claqua (background color)
Write the following code in the drawcolumncell event of DBGrid:

If (State = [gdselected]) or (State = [gdselected gdfocused]) then
Dbgrid1.canvas. Brush. Color: = clred; file: // The current row is displayed in red. Other rows use the light green background.
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );

4. Zebra Effect of line highlighting: not only highlight the current row, but also distinguish different columns (fields ).

File: // other attributes are set to the same as 3. Modify the above Code:
If (State = [gdselected]) or (State = [gdselectedgdfocused]) then
Begin
Case datacol mod 2 = 0
True: dbgrid1.canvas. Brush. Color: = clred; file: // red is displayed for the even column of the currently selected row.
False: dbgrid1.canvas. Brush. Color: = clblue; file: // the odd sequence of the currently selected row is blue.
End;
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );
End;

5. Horizontal zebra crossings, highlighted in red at the same time.

File: // other attributes are set to the same as 3. Modify the above Code:
Case table1.recno mod 2 = 0 of file: // judge based on the record number of the dataset
True: dbgrid1.canvas. Brush. Color: = claqua; file: // displays even rows in light green.
False: dbgrid1.canvas. Brush. Color: = clblue; file: // the odd number of rows in blue.
End;
If (State = [gdselected]) or (State = [gdselectedgdfocused]) then file: // display the selected row in red
Dbgrid1.canvas. Brush. Color: = clred;
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );

6. Bidirectional zebra effect: select different colors for the selected lines and use vertical zebra effect to distinguish different columns.

File: // other attributes are set to the same as 3. Modify the above Code:
Case table1.recno mod 2 = 0 of file: // judge based on the record number of the dataset
True: dbgrid1.canvas. Brush. Color: = claqua; file: // displays even rows in light green.
False: dbgrid1.canvas. Brush. Color: = clblue; file: // the odd number of rows in blue.
End;
If (State = [gdselected]) or (State = [gdselectedgdfocused]) then
Case datacol mod 2 = 0
True: dbgrid1.canvas. Brush. Color: = clred; file: // The even column of the currently selected row is in red.
False: dbgrid1.canvas. Brush. Color: = clgreen; file: // the odd sequence of the currently selected row in green.
End;
Dbgrid1.canvas. Pen. Mode: = pmmask;
Dbgrid1.defadrawcolumncell (rect
Datacol
Column
State );

The preceding six methods are used to set the colors of columns and rows in the data grid control. You can set special effects as needed.

Click the title of DBGrid to sort the query results. Keywords: DBGrid sorting

To sort the query results by clicking the title of DBGrid, you can use a general program. For example, you cannot add order by... in an SQL statement ..., because SQL may already contain order ..., in addition, when you click another title, you need to sort it separately to make it as desired as the resource manager.

Procedure tfhkdata. sortquery (column: tcolumn );
VaR
Sqlstr, myfieldname, tempstr: string;
Orderpos: integer;
Savedparams: tparams;
Begin
If not (column. Field. fieldkind in [fkdata, fklookup]) Then exit;
If column. Field. fieldkind = fkdata then
Myfieldname: = uppercase (column. Field. fieldname)
Else
Myfieldname: = uppercase (column. Field. keyfields );
While pos (myfieldname, ';') <> 0 do
Myfieldname: = copy (myfieldname, 1, pos (myfieldname, ';')-1) + ',' + copy (myfieldname, pos (myfieldname ,';') + 1,100 );
With tquery (TDBGrid (column. Grid). datasource. dataset) Do
Begin
Sqlstr: = uppercase (SQL. Text );
// If pos (myfieldname, sqlstr) = 0 Then exit;
If paramcount> 0 then
Begin
Savedparams: = tparams. Create;
Savedparams. Assign (Params );
End;
Orderpos: = pos ('order', sqlstr );
If (orderpos = 0) or (Pos (myfieldname, copy (sqlstr, orderpos, 100) = 0) then
Tempstr: = 'ORDER BY' + myfieldname + 'asc'
Else if pos ('asc ', sqlstr) = 0 then
Tempstr: = 'ORDER BY' + myfieldname + 'asc'
Else
Tempstr: = 'ORDER BY' + myfieldname + 'desc ';
If orderpos <> 0 then sqlstr: = copy (sqlstr, 1, OrderPos-1 );
Sqlstr: = sqlstr + tempstr;
Active: = false;
SQL. Clear;
SQL. Text: = sqlstr;
If paramcount> 0 then
Begin
Params. assignvalues (savedparams );
Savedparams. Free;
End;
Prepare;
Open;
End;
End;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.