DBGrid application skills

Source: Internet
Author: User
2003-12-11 21:31:47 Remove the automatic addition function of DBGrid

Procedure tform1.performance1change (Sender: tobject; field: tfield );
Begin
If tdatasource (sender). dataset. EOF then tdatasource (sender). dataset. Cancel;
End;

2003-12-11 21:34:39DBGrid moves the focus to the specified row and column

DBGrid is inherited from tcustomgrid. It has the col and row attributes, but it is protected and cannot be accessed directly. To handle this, you can:

Tdrawgrid (dbgrid1). Row: = row;
Tdrawgrid (dbgrid1). Col: = Col;
Dbgrid1.setfocus;
You can see the effect.

1. This method is absolutely problematic. It will cause chaos in DBGrid because DBGrid cannot locate the current record. If DBGrid is read-only, it will still cause some problems, for example, you can select multiple records that can only be selected. You can try it on your own.) If DBGrid is editable, the problem will be high because of the relationship between the current records, the data field you changed may not be in your imagination.
2. My common solution isProgramChange to (setting col is safe and there is no problem)

Query1.first;
Tdrawgrid (dbgrid1). Col: = 1;
Dbgrid1.setfocus;

This moves the focus to the first column of the first row.

2003-12-11 21:36:49Definition table

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;

2003-12-11 21:38:20Insert 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, including 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.

2003-12-11 21:39:03Lock the column on the left of DBGrid

When using delphi3 for database programming, I hope that the DBGrid component will lock the specified columns on the left without scrolling like the Foxpro browse command when displaying data, what method is used for implementation?

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 dgindicator of the options attribute of DBGrid to false, set fixedcols to 1.

2003-12-11 21:39:42Changes the color of some data of DBGrid.

You can change the color of the grid or text according to the data condition in the drawdatacell event of the DBGrid element.
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.

2003-12-11 21:40:29Practical Delphi Data Grid color effects

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 in the drawcolumncell event of DBGrid: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;
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. The program passed the test in delphi5.

2003-12-11 21:41:19Click 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;

2003-12-11 21:41:50DBGrid does not support the solution code for moving the cursor up or down (thanks to wangxian11)

Capture and process wm_mousewheel messages by yourself
Private
Oldgridwnd: twndmethod;
Procedure newgridwnd (VAR message: tmessage );
Public

Procedure tform1.newgridwnd (VAR message: tmessage );
VaR
Isneg: Boolean;
Begin
If message. MSG = wm_mousewheel then
Begin
Isneg: = short (message. wparamhi) <0;
If isneg then
Dbgrid1.datasource. dataset. moveBy (1)
Else
Dbgrid1.datasource. dataset. moveBy (-1)
End
Else
Oldgridwnd (Message );
End;

Procedure tform1.formcreate (Sender: tobject );
Begin
Oldgridwnd: = dbgrid1.windowproc;
Dbgrid1.windowproc: = newgridwnd;
End;

2003-12-11 21:44:39Display images in the DBGrid Control

If a field of the Blob type is set in the database to save the image, when you use the DBGrid control to display it, blob is displayed in the table, but the image cannot be displayed. Of course, there are some third-party controls that can display images, but it is not easy to find third-party controls, and some of the useful ones require payment. Can I display images in DBGrid? The answer is yes.
Add the following code to the ondrawcell event of DBGrid to display the image in the DBGrid control.
VaR
BMP: tbitmap;
Begin
If (column. Field. datatyp = ftblob) or (column. Field. datatyp = ftgraphic) then
Begin
BMP: = tbitmap. Create;
Try
BMP. Assign (column. Field );
Dbgrid1.canvas. stretchdraw (rect, BMP );
BMP. Free;
Except
BMP. Free;
End;
End;
End;
In a similar way, the memo field content can be displayed in DBGrid.
In addition, we recommend that you use the EMF Metafile when saving images to the database, so that the size of the database files will not change very astonishing. I have tried it, it is also a 400*300 image. If you use a bitmap to save more than 100 images, the size of the database file will reach nearly 20 mb, And the EMF vector image will be used to save the image, more than 800 KB is saved when more than 260 images are saved. The method for saving EMF vector images is similar to that for storing bitmaps, and the display in DBGrid is similar, however, the Blob field content cannot be directly assigned to the EMF file by assign, and it must be transferred through memorystream.

2003-12-11 21:45:42How to detect the current records and column information of DBGrid

How can I capture the record of the DBGrid where the cursor or mouse is currently located? I mean, the record where the cursor is located can be immediately displayed in another Edit

If your problem is corresponding to a group of Edit elements, we recommend that you use tdbedit or tdblabel to record the location;
If there is only one editbox, the content must always reflect the current column of the current record of DBGrid, you can write a program to update the editbox content in both the ondatachange event of datasource and the oncolenter event of DBGrid.
For example, the oncolenter event of DBGrid:

Procedure tform1.dbgrid1colenter (Sender: tobject );
Begin
If dbgrid1.selectedfield <> nil then
Edit1.text: = dbgrid1.selectedfield. asstring;
End;

However, oncolenter alone is not enough because oncolenter will not be triggered when the reversed square is moved up and down in the same column (the same column, the ondatachange event can be combined with the datachange event when the State is dsbrowse. It can be regarded as a change in the record location. The following program calls the oncolenter event handler of DBGrid:

Procedure tform1.datasource1datachange (Sender: tobject; field: tfield );
Begin
If performance1.state = dsbrowse then
Dbgrid1colenter (sender );
End;

2003-12-11 21:48:28How does DBGrid display checkbox selection input in the column of a non-Boolean field?

You can set the special content field to an explicit field in the dataset associated with DBGrid, and write the following code in the ongettext event:
Take table as an example:
Procedure tform1.table1myfield1gettext (Sender: tfield;
VaR text: string; displaytext: Boolean );
VaR PD: string;
Begin
Inherited;
PD: = table1.fieldbyname ('myfield1'). asstring;
If Pd = '1' then
Text: = '□'
Else
If Pd = '2' then
Text: = '▲'
Else
Text: = '√ ';
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.