DBGRID application series
Copyright Codesky.Net 2003-2005
Published: 2004-10-19 Keywords: unknown
DBGRID is one of the main means of displaying data in the Delphi language database programming. However, DBGRID default appearance has not seen monotonous and lack of ideas. In fact, we can fully achieve the purpose of beautifying DBGRID in our program. By programming, we can change DBGRID's head, grid, grid line foreground and background color, and the size and style of the related font. The following sample program demonstrates settings for DBGRID attributes, making the table displayed by Delphi as beautiful as the form in the web page. The operation of the sample program: Place the DBGRID1, Query1, DataSource1 on Form1, set the related properties, so that the DBGRID1 can display the data in the table. Then, type the following code in DBGRID1's OnDrawColumnCell event, and then run the program, you can see the magical result. This code is debugged in the Windows98, Delphi5.0 environment. procedure TMainForm.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var i: integer; beginif gdSelected in State then Exit; file: // header defined font and background Color: for i: = 0 to (sender as tdbgrid) .Columns.count-1 dobegin (Sender as tdbgrid) .COLUMNS [i] .title.font.name: = 'Song body'; file: // font (Sender AS) TDBGRID) .COLUMNS [I] .title.font.size: = 9; file: // Font Size (sender as tdbgrid) .COLUMNS [i] .title.font.color: = $ 000000FF; File: // Font Color (Snder as TdbGrid) .COLUMNS [i] .title.color: = $ 0000FF00; File: // Background Color (green) end; file: // Value change grid background color: if query1.recno mod 2 = 0 THEN (Sender as tdbgrid) .canvas.brush.color: = clinfobk file: // Define background color else (sender as tdbgrid) .canvas.brush.color: = RGB (191, 255, 223); file: / / Define background color file: // Defines the color of the grid line: dbgrid1.defaultdrawColumnCell (Rect, Datacol, Column, State); with (sender as tdbgrid) .canvas do file: // draws Border Border Border beginpen.color: = $ 00ff0000; File: // Define Brush Color (Blue) MoveTo (Rect.right, Rect.Bottom); File: // Paint Position Lineto (Rect.right, Rect.Bottom); File: // Draw blue Horizontal Pen.color : = $ 0000FF00; File: // Define Brush Color (Green) Moveto (Rect.right, Rect.top); File: // Brush Positioning Lineto (Rect.right, Rect.Bottom); File: // Draw Green End;
// procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var i: integer; beginif gdSelected in State then Exit; file: // change interlaced grid background Color: if adoquery1.recno mod 2 = 0 Then (sender as tdbgrid) .canvas.brush.color: = clinfobk file: // Define background color else (sender as tdbgrid) .canvas.brush.color: = RGB (191, 255, 223); file: // Define background color
File: // Defines the color of the grid line: dbgrid1.defaultdrawColumnCell (Rect, Datacol, Column, State); with (sender as tdbgrid) .canvas do file: // painted Border Baker BeginpenPenpen.color: = $ 00ff0000; File : // Define brush color (blue) Moveto (Rect.right, Rect.bottom); File: // Brush Positioning Lineto (Rect.right, Rect.Bottom); File: // Draw blue horizontal Pen. Color: = CLBTNFACE; File: / / Define Brush Color (Lan) MoveTo (Rect.right, Rect.top); File: // Brush Positioning Lineto (Rect.right, Rect.Bottom); File: // Draw Green END;
Table1 in BDE fails to pass, and the color has no interlaced changes.
Inserting other visual components Delphi in Delphi's DBGRID provides powerful DBGRID components to facilitate database application design. But if we use the DBGRID component, each get the focus (Grid) is just a simple text editing box, which is not convenient for users to enter data. Delphi also provides some other data components to facilitate user input, such as DBCombOBox, Dbcheckbox, etc., but these components have no DBGRID functionality. Can Delphi can make DBGRIDs like 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 is a component-dbedit component that floats on the grid. The grid you enter the data is actually a floating dbedit component, and the other unfolded places is just an image. So, inserting other visual components in DBGRID is a visual component that floats on the grid. Thus any component, including from a simple dbcheckbox to complex dialog box, can be inserted in DBGRID. Below is a step of inserting a DBCOMBOBOX component in DBGRID, using the same approach to insert other components.
1, create a new project in Delphi 4.0.
2, Data Access component board dragged on DataSource, Table, Data Controls component board on DBGRID, DBCOMBOBOX, four components to FORM1.
3. Set the properties of each component as follows:
rcf1 object properties set plant Form1 Caption 'SpinEdit inserted DBGrid components of the example in the' DataSource1 DataSet Table1Table1 DatabaseName DBDEMOSTableName 'teacher.DBF'Active TrueDBGrid1 DataSource DataSource1DBComboBox1 DataField SEXDataSource DataSource1Visible FalseStrings Items.' M '|' female 'Note: I'm here with TEACHER.DBF, it is to reflect the gender of the teachers, can only be "male" or "female".
4, DrawDATACELL event is to draw cells, when the field corresponding to the focus grid is consistent with the fields corresponding to the combo box, the moving combination box is on the grid that gets the focus, and the combo box is visible, thereby reaching in DBGRID The function of displaying DBCOMBOBOX is displayed on the column. Set the onDrawDataacell event of DBGRID1 as follows:
procedure TForm1.DBGrid1DrawDataCell (Sender: TObject; const Rect: TRect; Field: TField; State: TGridDrawState); beginif (gdFocused in State) thenbeginif (Field.FieldName = DBComboBox1.DataField) thenbeginDBComboBox1.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;
5 is not displayed when DBComboBox DBGrid specified cell is not in focus, the set DBGrid1 OnColExit event follows: procedure TForm1.DBGrid1ColExit (Sender: TObject); beginIf DBGrid1.SelectedField.FieldName = DBComboBox1.DataField thenbeginDBComboBox1.Visible: = false; end; END;
6. When DBGRID specifies the column to get focus, the DrawDataAsell event is just drawing a cell and displays dbcomboBox, but DBCOMBOBOX does not get focus, and the input of the data is on the cell. Tune the SendMessage this Windows API function in DBGRID1, which is transferred to DBCOMBOBOX, which reaches data input on DBCOMBOBOX. So set the keypress event as follows:
procedure TForm1.DBGrid1KeyPress (Sender: TObject; var Key: Char); beginif (key <> chr (9)) thenbeginif (DBGrid1.SelectedField.FieldName = DBComboBox1.DataField) thenbeginDBComboBox1.SetFocus; SendMessage (DBComboBox1.Handle, WM_Char, word (KEY), 0); END; END;
The program is debugged under the Chinese Windows 98, Delphi 4.015. I hope this article can make you more convenient and quick to develop database applications. When you lock the column of DBGRID, I hope that the DBGRID component you want to display the Browse command when displaying the data, and what method does not scroll like FoxPro?
We know that Delphi's TStringGrid has a property fixedcols to specify columns that do not scroll. Although TDBGRID cannot use this property directly, it is also possible to first function by forced type conversion, because both classes come from the TCUSTOMGRID class. Below we describe the specific usage as the DELPHI 3.0 Demos / DB / Ctrlgrid as an example. Add the following line during the TFMCTRLGRID.FORMSHOW of this example:
TstringGrid (dbgrid1) .fixedcols: = 2;
Run the program, when moving each column or so, the Symbol column will not move. In addition to this method, the following method can be used: first in the FORM declaration part
TYPE TMYGRID = Class (TDBGRID) End;
Then add in the TFMCTRLGRID.FORMSHOW process:
TMYGRID (DBGRID1) .fixedcols: = 2;
The two are slightly different from the form, but the essence is the same. We set FixedCOLS here for 2 because there is an indication column on the left side of the DBGRID component. If you set the DGIndicator of DBGRID to false, you should set FixedCOLS 1.
Make a few of the DBGRID to change the color of the lattice or text in the DBGRID component's DrawDATACELL event. Such as:
OnDrawDatacell (...) Beginwith Tdbgrid (Sender) Dobeginif (Condition) Thencanvas.TextOut (Rect.Left 4Rect.top 2
'The text to display, such as the form of the form');
And you will see how the DBGRID's display is overlapping. It is because the information overlap the data to be displayed by DBGRID and the data displayed by Textout: the field added in the Query component (right button on the component) Fields ... Player is set to false in the ONGETTEXT event that does not display the information.
Procedure TFORM1.Query1detail1getText (Sender: Tfield; DIST: STRING; DISPLAYTEXT: BOOLEAN); Begin // Decide not to display the obtained information false -> not display // to avoid TEXTOUT when DBGRID knows table information. Text overlapping displaytext: = false; end;
If it is handled with Delphi 3. For example: the red word is black and other as black words when its value is less than zero. In dbgrid.ondrawcolumncell (...):
Beginif Tablefield.asinteger <0 thendbgrid.canvas.font.color: = CLRedelsedbGrid.canvas.font.color: = CLBLACK; DBGRID.DEFAULTDRAWCOLUMNCELL (...);
This is still not necessary to rewrite the format specified for Field.
Batter Delphi Data Grid Color Special Effects Delphi Data Grid Control (TDBGRID) plays a very important role in displaying and editing a large amount of data in the database; however, while using data grid controls, it is often a large number of tables. The data is not easy to distinguish, and the operator is dazzling. How to improve the ease of use of grid controls, overcome this shortcomings? This paper puts forward a solution from changing the color configuration angle of the data grid. The following is the implementation method of the six special effects of the data grid control, as for how the data grid control and the data set are connected to the number.
1. Longitudinal zebra crossing effect: The odd number of the grid and the even column are displayed in different colors to distinguish between adjacent data columns. File: // Write the following code in DBGRID DrawColumnCell event:
Case Datacol Mod 2 = 0 OFTRUE: dbgrid1.canvas.brush.color: = CLBLUE; File: // Even Blue False: dbgrid1.canvas.brush.color: = Claqua; file: // 奇 列 用用 绿End; dbgrid1.canvas.pen.mode: = pmmask; dbgrid1.defaultdrawColumnCell (RectDataColColumnTate);
2. Longitudinal zebra crossing while highlighting the current cell effect: to highlight the currently selected field.
File: // Modify the above code to: Case Datacol MOD 2 = 0 OFTRUE: DBGRID1.CANVAS.BRUSH.COLOR: = CLBLUE; File: // Even Columns with Blue False: DBGrid1.canvas.brush.color: = Claqua ; file: // odd column with light green End; If ((State = [gdSelected]) or (State = [gdSelectedgdFocused])) thenIf Not DbGrid1.SelectedRows.CurrentRowSelected thenDbGrid1.Canvas.Brush.Color: = clRed; file: // The currently selected cell display red dbgrid1.canvas.pen.mode: = pmmask; dbgrid1.defaultdrawColumnCell (Rect Datacol Column State);
The above two methods highlight the display effect of the column.
3. The currently selected row is highlighted in the data grid. Set the DGROWSELECT attribute in the options attribute of the DBGRID control, and the Color property is written in the DBGRID DrawColumnCell event:
IF (state = [gdselected]) or (state = [gdselected gdfocused]))) "))") "ThendBgrid1.canvas.brush.color: = CLRED; File: // Current line with red display, other rows of light green dbgrid1.canvas .pen.mode: = pmmask; dbgrid1.defaultdrawColumnCell (RectDataColcolumnState);
4. The zebra crossing effect: highlights the current line and distinguishes different columns (fields).
File: // Other Properties Set the same 3, modify the above code to: IF (state = [gdselected]) or (state = [gdselectedGDFocused])) Thenbegincase Datacol Mod 2 = 0 OFTRUE: dbgrid1.canvas.brush.color: = CLRED; File: // The no-numbers of the currently selected row show red false: dbgrid1.canvas.brush.color: = CLBLUE; File: // The odd number of the currently selected row shows blue end; dbgrid1.canvas.pen.mode : = pmmask; dbgrid1.defaultdrawColumnCell (RectDataColColumnTate); END; 5. Transverse zebra crossing while highlighting the current effect.
File: // Other Properties Set the same 3, modify the above code to: Case Table1.Recno Mod 2 = 0 of file: // Depending on the record number of the data set True: dbgrid1.canvas.brush.color: = Claqua; File: // Even Light Green Display False: DBGrid1.canvas.brush.Color: = CLBLUE; File: // 数 Row Blue Represents End; IF ((state = [gdselected]) or (state = [gdselected ])) The file: // Select the row red display dbgrid1.canvas.brush.color: = CLRED; dbgrid1.canvas.pen.mode: = pmmask; dbgrid1.defaultdrawColumnCell (RectDataColColumnState);
6. Two-way zebra crossing effect: that is, the line is distinguished in different colors, while the line is divided into different columns in longitudinal zebra crossing.
File: // Other Properties Set the same 3, modify the above code to: Case Table1.Recno Mod 2 = 0 of file: // Depending on the record number of the data set True: dbgrid1.canvas.brush.color: = Claqua; File: // Even Light Green Display False: DBGrid1.canvas.brush.Color: = CLBLUE; File: // 数 Row Blue Represents End; IF ((state = [gdselected]) or (state = [gdselected ])) Thencase Datacol MOD 2 = 0 OFTRUE: DBGRID1.CANVAS.BRUSH.COLOR: = CLRED; File: // The ever-numbered number of red FALSE: DBGRID1.cANVAS.BRUSH.COLOR: = CLGreen; File: / / The odd number of odd columns of the currently selected line indicates End; dbgrid1.canvas.pen.mode: = pmmask; dbgrid1.defaultdrawColumnCell (RectDataColcolumnState);
The six methods described above are set on the columns of the data grid control, respectively, and the reader can set special effects according to their own needs. This program is tested in Delphi5.
Click on DBGRID Title to sort the query results: dbgrid sort
To achieve the title of DBGRID, you want to make a general program, not a general program, such as increasing the order by ... A Title is also sorted separately, the purpose is to want to do so like the resource manager. procedure TFHkdata.SortQuery (Column: TColumn); varSqlStr, myFieldName, TempStr: string; OrderPos: integer; SavedParams: TParams; beginif not (Column.Field.FieldKind in [fkData, fkLookup]) then exit; if Column.Field.FieldKind = fkData thenmyFieldName: = UpperCase (Column.Field.FieldName) elsemyFieldName: = UpperCase (Column.Field.KeyFields); while Pos (myFieldName, ';') <> 0 domyFieldName: = copy (myFieldName, 1, Pos (myFieldName, ';') - 1) ',' COPY (MyfieldName, POS (MyfieldName, ';') 1,100); with tQuery (tdbgrid (color) .datasource.DataSet) DOBEGINSQLSTR: = Uppercase (Sql.Text ); // if POS (MyfieldName, Sqlstr) = 0 THEN EXIT; if paramcount> 0 THENBEGINSAVEDPARAMS: = TParams.create; SavedParams.assign (params); end; orderpos: = POS ('Order', SQLSTR); IF ORDERPOS = 0) OR (POS (MyfieldName, Copy (Sqlstr, Orderpos, 100)) = 0) THENTEMPSTR: = 'Order by' myfieldname 'Asc'Else IF POS (' ASC ', SQLSTR) = 0 THENTEMPSTR: = 'Order By' MyfieldName 'Asc'elseTempstr: =' Order By ' MyfieldName ' DESC '; if Orderpos <> 0 Then Sqlstr: = COP y (SqlStr, 1, OrderPos-1); SqlStr: = SqlStr TempStr; Active: = False; Sql.Clear; Sql.Text: = SqlStr; if ParamCount> 0 thenbeginParams.AssignValues (SavedParams); SavedParams.Free; end Prepare; Open; end;
Remove DBGRID Auto Add Function Keywords: DBGRID
When moving to the last record, press "Next" to add a record, if you remove this feature procedure tform1.datasource1change (sender: Tobject; Field: tfield); beginif tdataroup (sender) .dataset.eof kiln TDataSource (Sender) ) .D; DBGRID does not support the mouse up and down mobile solution (thanks to Wangxian11) to capture WM_Mousewheel messages processed PrivateOldGridWnd: Twndmethod; Procedure: TMESSAGE; PUBLIC
procedure TForm1.NewGridWnd (var Message: TMessage); varIsNeg: Boolean; beginif Message.Msg = WM_MOUSEWHEEL thenbeginIsNeg: = Short (Message.WParamHi) <0; if IsNeg thenDBGrid1.DataSource.DataSet.MoveBy (1) elseDBGrid1.DataSource.DataSet .MOVEBY (-1) endelseoldgridwnd (message);
Procedure tform1.form; beginoldgridwnd: = dbgrid1.windowproc; dbgrid1.windowproc: = newGridWnd;
DBGRID moving focus to the specified row and column DBGRID inherited from tcustomgrid, it has a colounce, but it is protected, you can't access it directly, to process, 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 inside DBGRID because DBGrid cannot locate the current record. If DBGRID is read, it is still a problem, such as the record that can only be radically only radio. Multi-selection, etc. You can try it yourself). If DBGRID edits, you can be big, because the current record relationship, the data field you change is likely to be the 2 I have a common solution. Change the program to (casually set col is safe, no problem)
Query1.first; tdrawgrid (dbgrid1) .col: = 1; dbgrid1.setfocus;
This allows the focus to move to the first column of the first line.
How to make the color of the DBGRID grid change with the data value in this grid? In the interface, sometimes in order to highlight the various characteristics of the data (eg, too much or too small), it is necessary to change the font or color, this article is a description of this situation.
How to make the color of the DBGRID grid changes with the data value in this grid. As the "grid of <60 is red? Data control components DBGRID in Delphi are the most important and most common components for reflecting data sheets. In the application, if DBGRID is displayed in a colorful manner, it will increase its visibility, especially when there are some important or need to be alerted, you can change the rows or columns of the data and the background of the rows and backgrounds. colour. DBGRID Properties DEFAULTDRAWING is used to control Cell (grid) drawing. If DEFAULTDRAWING is set to true, it means that Delphi uses DBGRID's default drawing method to make a grid and the data contained therein, and data is drawn in accordance with the DisplayFormat or EditFormat feature of the TField member connected to a particular column; If DBGRID's defaultdrawing feature is set to false, Delphi does not draw grid or its content, and you must provide your own draw routine (self-drawing function) in TDBGRID's OnDrawDataAsell event. An important attribute that will be used herein: Canvas Canvas, many components have this property. Canvas represents the surface currently displayed DBGRID. If you specify another custom display content and style to the Canvas of the DBGRID object, the DBGRID object will display the Canvas property value on the screen. When applying, it involves the brush attribute of Canvas and the FillRect method and the Textout method. The Brush property specifies the image, color, style, and access to the Windows GDI object handle, and the FillRect method uses the current brush property to populate the rectangular area, and the method TextOut outputs the text content of Canvas. The following examples describe how to display colored DBGRIDs in detail. In the example, there is a DBGRID component, followed by a SpineDit component for generating a color filter condition, and the ColorGrid component is free to select the foreground and background of the data unit.
1. Create a Project called ColordBGrid, put the desired component in turn in its form form1, and set the attribute as the corresponding value, specifically listed below:
Table1 DatabaseName: DBDEMOSTableName: EMPLOYEE.DBActive: True; DataSource1 DataSet: Table1 DBGrid1 DataSource1: DataSource1DefaultDrawing: False SpinEdit1 Increment: 200Value: 20000 ColorGrid1 GridOrdering: go16 * 1
2. Write a response program for the DBGRID1 component onDrawDatacell event:
File: // The program written here is the case where the grid is red, the other can push Procedure TFORM1.DBGRID1DRAWDATAC1.DBGRID1DRAWDATAC1.DBGRID1DRAWDATACELL (SENDER: TFIELD: TFIELD; STATE: TGRIDDRAWSTATE); Begin IF Table1.Fieldbyname ( 'Salary') value <= SpinEdit1.value then DBGrid1.Canvas.Brush.Color: = ColorGrid1.ForeGroundColor else DBGrid1.Canvas.Brush.Color: = ColorGrid1.BackGroundColor; DBGrid1.Canvas.FillRect (Rect). DBGrid1.canvas.textout (Rect.Left 2, Rect.top 2, Field.Asstring); END; This process is the role of this process is when the condition given by SpineDit1 is satisfied, such as the 'Salary' variable is lower than or equal to Spinedit1.Value DBGRID1 records in the foreground color of ColorGrid1, otherwise it is displayed in the background color of ColorGrid1. Then call the DBGRID's CANVAS fill process and the text output process to re-draw the DBGRID screen.
3. Write a response code for the onchange event for SpineDit1 components:
Procedure tform1.spinedit1change (sender: TOBJECT); begin dbgrid1.refresh; file: // Refresh is required, be refreshed, End;
Refresh DBGRID1 when the value of the SpineDit1 member changes.
4. Write a response code for the onchange event of ColorGrid1:
Procedure tform1.colorgrid1change (sender: TOBJECT); begin dbgrid1.refresh; file: // Refresh is required, be refreshed, End;
When the value of ColorGrid1 changes, the right button or left mouse button of the mouse is re-refreshed with the ColorGrid1.
5. Write a response code for the oncreate event of the Form1 form (main form):
Procedure TFORM1.FormCreate (Sender: TOBJECT); Begin Colorgrid1.ForeGroundIndIndex: = 9; ColorGrid1.BackgroundIndex: = 15;
When you create the main window, set the initial value of ColorGrid1 as gray, the background is white, that is, the font color of DBGrid is gray, background color is white.
6. Now you can compile and run the ColordBGRID program. When using the left button or right-click ColorGrid1, the font and background color of the DBGRID will change.
In this article, it is simply shown that the principle of displaying DBGRID in color is displayed. Of course, it can also increase the complexity of the program so that it is actually used. The same truth, you can also extend this method to other components with the Canvas property, allowing the application's user interface more friendly.
Decades if the Grid has a scroll bar? This is a tip, if it is a unified words for the style, don't use it. :)
. . .
if (GetWindowlong (Stringgrid1.Handle, GWL_STYLE) and WS_VSCROLL) <> 0 thenShowMessage ( 'Vertical scrollbar is visible!'); if (GetWindowlong (Stringgrid1.Handle, GWL_STYLE) and WS_HSCROLL) <> 0 thenShowMessage ( 'Horizontal scrollbar is visible ! '); . .
The synchronous scroll of two grid is actually produced, and sometimes several grids need to synchronize scrolling to reduce the user's operation. I hope that the code below has a certain reference value.
{1.}
Unit syncstringgrid;
Interface
Useswindows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Grids
TypetSynck Ind = (Skboth, Skvscroll, Skhscroll); TsyncStringGrid = Class (TSTRINGGRID)
privateFInSync: Boolean; FsyncGrid: TSyncStringGrid; FSyncKind: TSyncKind; {Private declarations} procedure WMVScroll (var Msg: TMessage); message WM_VSCROLL; procedure WMHScroll (var Msg: TMessage); message WM_HSCROLL;
protected {protected declarations}
Public {public declarations} {public declarations} {public Dosync (MSG, WPARAM: Integer; lParam: longint); Virtual;
Published {published Declarations}}} tycgrid: TsyncStringGrid Read FsyncGrid Write FsyncGrid; Property Synckind: Tsynck Ind Read Fsynckind Write Fsynck IndiaNCKIND WRITE FSYNCKIND Default Skboth;
PROCEDURE register;
IMPLEMentation
Procedure Register; BeginRegisterComponents ('Samples', [TsyncStringGrid];
procedure TSyncStringGrid.WMVScroll (var Msg: TMessage); beginif not FInSync and Assigned (FSyncGrid) and (FSyncKind in [skBoth, skVScroll]) thenFSyncGrid.DoSync (WM_VSCROLL, Msg.wParam, Msg.lParam); inherited; end;
procedure TSyncStringGrid.WMHScroll (var Msg: TMessage); beginif not FInSync and Assigned (FSyncGrid) and (FSyncKind in [skBoth, skHScroll]) thenFSyncGrid.DoSync (WM_HSCROLL, Msg.wParam, Msg.lParam); inherited; end;
Procedure TsyncStringGrid.dosync (MSG, WPARAM: INTEGER; LPARAM: longint); Beginfinsync: = true; Perform (MSG, WPARAM, LPARAM); FINSYNC: = FALSE; END; END.
{**************************************}
{2.} privateGridProc1, OldgridProc2: TwndMethod; Procedure: tMessage; Procedure Grid2windowProc (Var message: tMessage);
PUBLIC {...}
Procedure TFORM1.GRID1WINDOWPROC (VAR Message: tMessage);
BeginoldgridProc1 (Message); if ((Message.msg = WM_VScroll) or (Message.msg = WM_HScroll) or Message.msg = WM_MouseWheel). ThenbeginoldGridProc2 (MESSAGE); end; end;
procedure TForm1.Grid2WindowProc (var Message: TMessage); beginOldGridProc2 (Message); if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL) or (Message.msg = WM_Mousewheel)) thenbeginOldGridProc1 (Message); end; end ;
procedure TForm1.FormCreate (Sender: TObject); beginOldGridProc1: = StringGrid1.WindowProc; OldGridProc2:;: = Grid1WindowProc; StringGrid2.WindowProc: = StringGrid2.WindowProc StringGrid1.WindowProc = Grid2WindowProc; end;
When the color of each line of DBGRID is used in Delphi, the color of the DBGRID is used to use the DBGRID control. Each column can be arbitrarily changed, but it is difficult to change the color of each row, then do not re-reproduce new controls. In the case, there is a good way to let DBGRID change each line color according to the user yourself. The answer is yes, and a simple method is introduced below.
To change the color of each line of DBGRID, as long as you want to change the crow of colors in the OnDrawColumnCell event, and specify the canvas.brush.color property of DBGRID and set the canvas.pen.mode property into pmmask, then call DBGRID's defaultdrawColumnCell Method can be. Note that before changing these two properties, you must first protect the value of the original canvas.brush.color property. After the regulator is completed, the original attribute value is changed back, now in the Delphi / DMOS / DB / ClientMD directory. The program clintproj.dpr is an example, which is a brief description. Here is a colors that disconnects the combined parts of the grid membergrid in the program, becomes a black, other non-conditional rows of colors for normal fonts, white backgrounds, Only in the DrawColumnCell event, the conditions are all other unchanged, as follows:
procedure TClientForm.MemberGridDrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); var oldcolor: tcolor; oldpm: tpenmode; beginif DM.ProjectTEAM_LEADER.Value = DM.Emp_ProjEMP_NO.Value then { Set the condition of the changing row} membergrid.canvas.font.style: = [fsbold]; MemberGrid.defaultdrawColumnCell (Rect, Datacol, Column, State); {The above is the original content of the demo, the following is increasing part} IF DM .ProjectTEAM_LEADER.Value = DM.Emp_ProjEMP_NO.Value then {sets the row discoloration condition} beginoldpm: = MemberGrid.Canvas.pen.mode; oldcolor: = MemberGrid.Canvas.Brush.color; MemberGrid.Canvas.Brush.color: = clyellow; MemberGrid.Canvas.pen.mode: = pmmask; MemberGrid.DefaultDrawColumnCell (Rect, DataCol, Column, State); MemberGrid.Canvas.Brush.color: = oldcolor; MemberGrid.Canvas.pen.mode: = oldpm; end END; feeling that this method is the same as the principles of the previous color control methods, all through the onDrawColumncell event to achieve colorful and eye-catching features. :) How to support multiple records in DBGRID This document comes from abroad, it is very useful, it is useful, it is recommended to learn to use. [Question]: How to do multi-selecting records in TDBGrid When you add [dgMultiSelect] to the Options property of a DBGrid, you give yourself the ability to select multiple records within the grid.The records you select are represented as bookmarks and? Are Stored In The SelectedRows Property.The SelectedRows Property Is An Object of Type TBOOKMARKLIST. The Properties and Methods Are Described BELOW.
// Property SELECTEDROWS: TBOOKMARKLIST READ FBOOKMARKS;
// TBookmarkList = class // public {* The Clear method will free all the selected records within the DBGrid *} // procedure Clear; {* The Delete method will delete all the selected rows from the dataset *} // procedure Delete; {* The Find method determines whether a bookmark is in the selected list *.} // function Find (const Item: TBookmarkStr; // var index: Integer): Boolean; {* The IndexOf method returns the index of the bookmark within the . Items property *} // function IndexOf (const Item: TBookmarkStr): Integer; {* The Refresh method returns a boolean value to notify whether any orphans were dropped (deleted) during the time the record has been selected in the grid The. refresh method can be used to update the selected list to minimize the possibility of accessing a deleted record *} // function Refresh:. Boolean; True = orphans found {* The Count property returns the number of currently selected items in the DBGrid *} // Property Count; {* The CurrentrowSelected Property R . Eturns a boolean value and determines whether the current row is selected or not *} // property CurrentRowSelected: Boolean // read GetCurrentRowSelected // write SetCurrentRowSelected; {* The Items property is a TStringList of TBookmarkStr *} // property Items [Index : Integer]: TBOOKMARKSTR / / READ GETITEM; DEFAULT; / / END; Unit Unit1;
Interface
Useswindows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls, Grids, DBGRIDS, DB, DBTABLES
typeTForm1 = class (TForm) Table1: TTable; DBGrid1: TDBGrid; Count: TButton; Selected: TButton; Clear: TButton; Delete: TButton; Select: TButton; GetBookMark: TButton; Find: TButton; FreeBookmark: TButton; DataSource1: TDataSource; procedure countClick (Sender: TObject); procedure SelectedClick (Sender: TObject); procedure ClearClick (Sender: TObject); procedure DeleteClick (Sender: TObject); procedure SelectClick (Sender: TObject); procedure GetBookMarkClick (Sender: TObject); procedure FindClick (Sender: TOBIECT); Private {private declarations} public {public declarations}} end; varform1: tformy; {
IMPLEMentation
{$ R * .dfm}
file: // Example of the Count propertyprocedure TForm1.CountClick (Sender: TObject); beginif DBgrid1.SelectedRows.Count> 0 thenbeginshowmessage (inttostr (DBgrid1.SelectedRows.Count)); end; end;
file: // Example of the CurrentRowSelected propertyprocedure TForm1.SelectedClick (Sender: TObject); beginif DBgrid1.SelectedRows.CurrentRowSelected thenshowmessage ( 'Selected'); end;
File: // Example of the Clear methodProcedure TFORM1.CLEARCLICK (Sender: TOBJECT); begindbgrid1.selectedRows.clear;
File: // Example of the delete methodProcedure TFORM1.DELETECLICK (Sender: TOBJECT); begindbgrid1.selectedRows.delete;
{* This example iterates through the selected rows of the grid and displays the second field of the dataset.The Method DisableControls is used so that the DBGrid will not update when the dataset is changed. The last position of the dataset is saved as a TBookmark .The IndexOf method is called to check whether or not the bookmark is still existent.The decision of using the IndexOf method rather than the Refresh method should be determined by the specific application *} procedure TForm1.SelectClick. (Sender: TObject); varx : word; TempBookmark: TBookMark; beginDBGrid1.Datasource.Dataset.DisableControls; with DBgrid1.SelectedRows doif Count> 0 thenbeginTempBookmark: = DBGrid1.Datasource.Dataset.GetBookmark; for x: = 0 to Count - 1 dobeginif IndexOf (Items [x] )> -1 thenbeginDBGrid1.Datasource.Dataset.Bookmark: = Items [x]; showmessage (DBGrid1.Datasource.Dataset.Fields [1] .AsString); end; end; end; DBGrid1.Datasource.Dataset.GotoBookmark (TempBookmark) DBGRID1.DataSource.DataSet.FreeBookmark (TempBookmark); DBGRID 1.DataSource.DataSet.EnableControls;
{* This Example Allows you to set a bookmark and and then search for the bookmarked record for the bookmarked record with the dbgrid. *}
File: // sets a bookmarkprocedure TFORM1.GetBookMarkClick (Sender: Tobject); BeginBookmark1: = dbgrid1.datasource.DataSet.getBookmark;
file: // Frees the bookmarkprocedure TForm1.FreeBookmarkClick (Sender: TObject); beginif assigned (Bookmark1) thenbeginDBGrid1.Datasource.Dataset.FreeBookmark (Bookmark1); Bookmark1: = nil; end; end;
file: // Uses the Find method to locate the position of the bookmarked record within the selected list in the DBGridprocedure TForm1.FindClick (Sender: TObject); beginif assigned (Bookmark1) thenbeginif DBGrid1.SelectedRows.Find (TBookMarkStr (Bookmark1), z ............... ..
Another way to control each line color in Delphi is a problem with DBGRID in Delphi, how to make each line of color in DBGRID in accordance with the user's own wishes. When I first saw this problem, we thought it was very simple, so I immediately prepared to solve it. As a result, it was found that it was not that case, and the traditional method could not work. I have been sitting at 4 am in front of the computer, constantly debugging, fortunately, with a point of programming experience that usually accumulate, I finally found the key key of opening the door. Now it is fully charged for everyone to enjoy.
1. The establishment of the data sheet is selected in the Delphi tool menu, and a data sheet named Example.db is created under the database DBDemos. The fields and contents of the data table are as follows: 2. Create a TDBGRID-based TColoredDBGRID component in the Delphi component menu, select New Component, make the following settings in the pop-up dialog:
Annestor type = tdbgridclass name = tcoloreddbgrid
Then click the OK button, Delphi automatically completes the definition of the basic framework of the component. Add an OnDrawColoredDBGRID event and make it appear in the Events of the Object Inspector to set the conditions for changing the colors in the application. Heavy duty Drawcell method can only draw units themselves. You cannot set the color by OnDrawColumncell, because the color of the onDrawColumncell change cell will again trigger OnDrawColumncell again. Below is the source program of the created component.
3. Establish an application to verify. Select NEW to create new application engineering Project1 and main forms FORM1 in the Delphi file menu, set the Form1's CAPTION attribute to "Controlling the DBGRID Color Color." Add Data Source, Table, Button, and ColoredDbGrid components on the main form. Setting the properties of each component as follows:
Table1.Database = 'dbdemos'table1.tablename =' example.db'dataroup1.dataset = table1coloreddbgrid1.datasource = Datasource1Button1.caption = 'Exit'
Enter the following code in the COLOREDDBGRIDDDDBGRID event, set by WAGE to determine the color of the coloreddbgrid1.
procedure TForm1.ColoredDBGrid1 DRawColoredDBGrid (Sender: TObject; Field: TField; var Color: TColor; var Font: TFont); Varp: Integer; beginp: = Table1.FindField ( 'wage') .AsInteger; file: // get the current record The value of the WAGE field. IF (P <500) The begin file: // The program will set the color of each row according to the WAGE value. Color: = CLGreen; font.style: = [fsitalic]; File: // Not only can you change the color, but also change the font end; if (p> = 500) AND (P <800) ThenColor: = CLRED; if (p > = 800) THEN BEGINCOLOR: = CLMAROON; font.style: = [fsbold]; end; end; file: // Run with the 'exit' button. Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT); beginclose; END; displaying multi-database in a DBGRID in database programming, unnecessarily impossible to put all database fields of the application operation in a database file. The correct database structure should be: put the database field into multiple database files, and the relevant database contains a unique key field that can be set in the multi-database structure. For example: To prepare a personnel management program, to simplify the demo, only two databases, each database only established two fields. Personal Profile Jianjie.dbf 1. The establishment of the database enters Database Desktop, the establishment of the database structure is as follows: jianjie.dbf number field name: Bianhao Size: 4 TYPE: Number Name Field Name: Xingming Size: 10 Type: Character
Gongzi.dbf number field name: Bianhao Size: 4 TYPE: Number salary field name: gongzi size: 4 DEC 2 TYPE: NUMBER
Note: The size, TYPE of the Bianhao field of the two databases must be consistent. In fact, the two database files can be distributed on different computers of the network to facilitate demonstrations, respectively, to "c: /test/jianjie.dbf" and "c: /test/gongzi.dbf", respectively.
2. The application of the application launches Delphi, create a new project, add the Query control query11 in the form, and the DatabaseName property is set to C: / Test;
Join the DataSource control DataSource1, the DataSet property is set to query1; join the DBGRID control DBGRID1, the DataSource property is set to DataSource1, set the query1.sql attribute to
Select Distinct A.bianhao, A.XINGMING, B.GongziFrom "jianjie.dbf" a, "gongzi.dbf" bwhere a.bianhao = B.bianhao
Then set the query1.enabled attribute to True, do not compile, DBGRID1 will display: bianhao, xingming, gongzi three fields. If there is record in jianjie.dbf and gongzi.dbf, the record will be displayed. Because of the boundary, this article only introduces the general method of displaying multiple database contents in DBGRID, readers can improve on this, so that this method can better adapt to your needs. How to get the carriage back in the DBGRID to the right movement in the Form.onkeyPress event:
IF key = # 13 Then if ActiveControl = dbgrid1 the begin TdbGrid (activeControl) .SelectedIndex: = TDBGRID (ActiveControl) .selectedIndex 1; Key: = # 0;
There are 2 points to pay attention: 1. When the cursor reaches the rightmost right column, press Enter, the cursor will stay in place. 2.Key: = # 0
DBGrid copied from the recording procedure TForm1.DBGrid1DblClick (Sender: TObject); varx: integer; HadToOpen: boolean; beginwith Sender as TDBGrid do beginHadToOpen: = not tTarget.Active; if HadToOpen thentTarget.Active: = True; tTarget.Append; for x: = 0 to FieldCount - 1 docase Fields [x] .DataType offtBoolean: tTarget.FieldByName (Fields [x] .FieldName) .AsBoolean: = Fields [x] .AsBooleanftString: tTarget.FieldByName (Fields [x] .FieldName) .Sstring: = FIELDS [x] .sstringftfloat: Ttarget.fieldByname (Fields [x] .fieldname) .asfloat: = FIELDS [x] .asfloatftinteger: Ttarget.fieldByname (Fields [x] .fieldname) .asinteger: = fields [ x] .asintegerftdate: Ttarget.fieldbyName (Fields [x] .fieldname) .asdatetime: = Fields [x] .asdatetime; end; ttarget.post; if Hadtoopen lifetarget.active: = false; end;
Use of complex options DBGrid (see How to choose can support a number of records in a DBGrid) procedure TForm1.SelectClick (Sender: TObject); varx: word; TempBookmark: TBookMark; beginDBGrid1.Datasource.Dataset.DisableControls; with DBgrid1.SelectedRows doif Count <> 0 thenbeginTempBookmark: = DBGrid1.Datasource.Dataset.GetBookmark; for x: = 0 to Count - 1 dobeginif IndexOf (Items [x])> -1 thenbeginDBGrid1.Datasource.Dataset.Bookmark: = Items [x]; showmessage (DBGrid1.Datasource.Dataset.Fields [1] .AsString); end; end; end; DBGrid1.Datasource.Dataset.GotoBookmark (TempBookmark); DBGrid1.Datasource.Dataset.FreeBookmark (TempBookmark); DBGrid1.Datasource.Dataset. EnableControls; End; Drag & DROP in DBGRID Discovery in the program, if the user can make the user directly drag and drop to a dbgrid, it will be very convenient, but found during the programming process It seems that drag and drop can only drag and drop to the current record, if you want to drag and drop to other records, you can't let users choose to record, then drag and drop. Later, through the study, when using the mouse point DBGRID, DBGRID will automatically move the record pointer to the recorded record, which gives me a thinking, let the program simulate a click on DBGRID to let the cursor move to On the record, you can write the drag and dropped data into the dbgrid. Through the fact that this idea is feasible. Below, I will tell me my approach: 1) First put a dbgrid on Form, and it can display records, (this is relatively simple, don't say more) 2) Playing an edit3 on Form) Modify the attribute of the EDIT To change DragMode to Dmautomatic, let the user can drag and drop 4) Add the following code in the DBGRID Dragover event: let it receive Drag & Drop
Procedure tForm1.dbgrid1dragover (Sender, Source: Tobject; X, Y: Integer; State: TDRAGSTATE; VAR Accept: boolean; beginaccept: = true;
5) Add the following code in the DBGRID DragDrop event: Let it automatically jump to the record specified by the cursor
procedure TForm1.DBGrid1DragDrop (Sender, Source: TObject; X, Y: Integer); beginif Source <> Edit1 then exit; with Sender as TDbGrid do beginPerform (wm_LButtonDown, 0, MakeLong (x, y)); PerForm (WM_LButtonUp, 0 , Makelong (x, y); selectedfield.dataset.edit; selectdfield.Asstring: = Edit1.Text; end;
At this point, we have achieved the desired function, where Perform is a general method of tControl to bypass the message loop of the Windows itself, and send the message directly to the contract, please refer to the help of Delphi. How to make DBGRID's pointer not move? [Question]: I use DBGRID to display the contents in Table, now I want to read the data in Table from the head to the end, with table1.first, next to make the pointer in DBGRID also followed, how can I make this time DBGRID? The pointer inside does not move?
[Answer]: Use the following code:
WITH DATASET DO TRY DISABLECONTROLS; DO_SMETHING; FINALLY EnableControls;
How to dynamically update the color of DBGRID? (Please refer to "How to make the color of the DBGRID grid change with the data value in this grid?") DBGRID control is a control of the display database with many user interfaces. The following programs tell you how to display content Change the display color of the font. For example, if the population of a city is greater than 2 million, we let it show blue. The control event used is DBGrid.ondrawColumecell.
procedure TForm1.DBGrid1DrawColumnCell (Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); beginif Table1.FieldByName ( 'Population') AsInteger> 20000000 thenDBGrid1.Canvas.Font.Color:. = clBlue DBGRID1.DEFAULTDRAWCOLUMNCELL (Rect, Datacol, Column, State);
The above example is simple, but you can expand according to your own needs, such as the font also change, etc., or even call the drawn function to draw a red circle on the number.
Using the DBGRID display date When you use the DBGRID control, it is 2 digits, but we need to display the date after walking into 2000, such as: 1998,2001. In the database, only 4 digits will be displayed after 2000. What should I do? Let's let this field also display 4 digits in the DBGRID control: Double-click the Table1 control, there will be a Form1.Table form, right click, select Add Fields ..., select the date field, press OK, Form There is a date field name of the database. The field name of the point date is displayed. There is an information on this field in the Properties box, and there is a DispalyFormat, enter YYYY.MM.DD in this display format, then DBGRID control appears A complete date.
Implement another idea to drag and drop in the TDBGRID control (please refer to DRAG & DROP on DBGRID) in DBGRID, in this unit, custom TMYCUSTOMDBGRID = Class (TCUSTOMDBGRID), then reference:
TMYCUSTOMDBGRID (DBGRID1) .MOUsedown (...) or dBGRID1 AS TMYCUSTOMDBGRID) .MOUsedown (...).
How to set the Enter key in the DBGRID table is equivalent to single click? [Routines]: Place Table1, DataSource1, DBGRID1, set the connection between Table1, DataSource1, DBGRID1, set the connection between DBGRID1. Then: procedure TForm1.DBGrid1KeyPress (Sender: TObject; var Key: Char); beginwith DBGrid1 doif Key = # 13 thenDBGrid1CellClick (Columns [SelectedIndex]); end; procedure TForm1.DBGrid1CellClick (Column: TColumn); beginwith DBGrid1 doshowmessage (format ( 'ROW =% d', [SELECTEDINDEX]); END;
Delphi's drop-down list and find field programming method data grid are very popular data inputs and display forms, like everyone familiar with Excel, VFP, powerful brows, etc., for the majority of programmers. When using the Delphi development database application system, use the data grid DBGRID to enter the data, some fields only allow for a few fixed strings, such as the storage period of the archives, only "permanent", "long-term" and "short-term" three Can you choose from a drop-down list, which is convenient to input and avoid input errors? There are also some fields, such as unit numbers in the employee information library (more detailed information in additional unit libraries), when entering and displaying employee data, can be operated without the unit number, alternative to more intuitive What about the unit name in the unit library? The answer is affirmative, Delphi's data grid control DBGRID, supports the drop-down list and finding the field programming, and the programmed process is visual, and does not need to write a row statement.
First, the drop-down list in DBGRID implements a drop-down list in the DBGRID grid, sets a list of Picklist strings in DBGRID, and the initial number value DropDownRows can be used. Taking the origin field (string type) in the staff information library as an example, the specific design steps are as follows: 1. Place Table1, DataSource1, DBGRID1, DBNAVIGATOR1, etc. on the form, press the table to set the properties of each object:
------------------------------------------------------ --------------------------------- Table1 Database Sy1Table Zgk.dbf file: // Staff Information Database Datasource1 Dataset Table1dbGrid1 Datasource DataSource1dbnavigator1 DataSource Datasource1 ------------------------------------------ 2, double click Table1 In the pop-up FORM1.TABLE1 window, use the right click to pop up the shortcut menu, click the Add Fields menu item; after selecting all the fields, press the OK button.
3. Modify the DISPLAYLABEL attribute of step 2's new field. Take the table1zgbh field as an example, select Table1zGBH in the Object Inspector window, modify the property DisplayLabel = employee number, and the remaining fields are similar.
4. Double-click DBGRID1. In the pop-up DBGRID1.COLUMNS window, click the Add All Fields button to increase all fields of Table1. 5, in the Editing DBGRID1.COLUMNS window, select JG this line, switch to the Object Inspector window, modify its picklist.strings as "Hubei Zhijiang City (Renewal) Beijing (Renewal) Henan Pingdingshan City (Renewal) Zhejiang Deqing City
6. Write a statement in the Form1.onCreate event:
Table1.open;
7, F9 runs, click on a recorded born field with the mouse, and a button appears on the right, click this button to display a drop-down list, including the four rows of strings entered in step 5, and can be selected with the mouse. Of course, you can also enter a string in the drop-down list.
Second, the lookup field in DBGRID The so-called lookup field (Lookup Field), the value of a key field in dbgrid comes from the corresponding field of another database. Using Find field technology, not only can effectively avoid input errors, but also DBGRID's display mode is more flexible, and the key fields are not displayed, and the data of another field corresponding to the source database is displayed. ---- For example, we display and edit employee information in dBGrid, including employee numbers, employee names, origin, unit numbers, and unit numbers from another database table - unit library, called "unit number" Field. If we directly display and edit the unit number, it will face 1, 2, 3, etc., very intuitive numbers, and the editor is extremely easy to go wrong. But if the display and editing is the corresponding unit name in the unit library, it will be very intuitive. This is the benefit of the supported find field supported by DBGRID.
Realizing the search field of DBGRID does not require any statement, the specific design steps are as follows: 1. Place Table1, Table2, DataSource1, DBGRID1, DBNAVIGATOR1, etc. on the form, press the table to set the properties of each object:
------------------------------------------------------ -------------------------------- Table1 Database Sy1Table Zgk.dbf file: // Staff Information Base Table2 Database SY1TABLE DWK . DataSource1 DataSet table1dbgrid1 DataSource Datasource1dbnavigator1 DataSource Datasource1 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------- 2, double-click Table1, in the pop-up Form1.Table1 window, use the right-click to pop up the shortcut menu, click the Add Fields menu item; after selecting all the fields, press the OK button.
3. Modify the DISPLAYLABEL attribute of step 2's new field. Take the table1zgbh field as an example, select Table1zGBH in the Object Inspector window, modify the property DisplayLabel = employee number, and the remaining fields are similar.
4, set table1dwbh.visible = false.
5, in the Form1.Table1 window, use the right-click to pop up the shortcut menu, click the New Field menu item, add a lookup field DWMC, set the corresponding properties in the pop-up window, press the OK button to confirm; in the Object Inspector window, set Table1DWMC. DisplayLabel = Unit name. 6. Write a statement in the Form1.onCreate event:
Table1.open;
7. Press F9 to run, when the light is shifted to a recorded unit name field, click on the field with the mouse, that is, a drop-down list, click the lower arrow on the right, and select it in the drop-down list. It can be seen here that the contents of the drop-down list come from the unit library and cannot enter other content.
Third, the drop-down list and find fields in DBGRID Although the drop-down list and lookup field in dbgrid appear in the form of the following list, there is a big difference. 1. Use the drop-down list set by the PickList property, and its data is manually entered, although it can also be modified in the program, but the dynamic characteristics clearly extract data from the additional database table directly.