Re: on col exit dbgrid
Posted by webmaster Guido on April 10, 2001 at 18:59:07:
In Reply to: on col exit dbgrid posted by p12114 andrew on April 05, 2001 at 23:25:53:
: I need the syntax to use the oncolexit in a dbgrid. I want to be able to select by colname or by the col index or both.
procedure TForm1.DBGrid1ColEnter(Sender: TObject); begin Table1.IndexFieldNames := DBGrid1.SelectedField.FieldName; end;
If you have less indexes than columns, you should do some checking before switching to another index. In the next example, there are only indexes for the first 3 fields of the table:
procedure TForm1.DBGrid1ColEnter(Sender: TObject); begin // Field-numbers start at 0 if DBGrid1.SelectedField.FieldNo < 3 then Table1.IndexFieldNames := DBGrid1.SelectedField.FieldName; end;
Whn some of the index definitions contain more than one field, or when you use a dBAse table with "expressions" in its indexes, then you have to use the table's IndexName property.
Example: the indexes are called CustID, CustNameID (combining the customer's name and ID), and CustType. The DBGrid has columns for ID, Name, and Type, plus some more columns for other customer data. The event handler becomes something like:
procedure TForm1.DBGrid1ColEnter(Sender: TObject); begin case DBGrid1.SelectedField.FieldNo of 1: Table1.IndexName := 'CustID'; 2: Table1.IndexName := 'CustNameID'; 3: Table1.IndexName := 'CustType'; else // change nothing, use the current index end; end;
Of course, you can use the fieldname of the selected column instead of the field-number, but then you can't write it as a "case" construction:
procedure TForm1.DBGrid1ColEnter(Sender: TObject); var ColName: string; begin ColName := UpperCase(DBGrid1.SelectedField.FieldNam e); if ColName = 'ID' then Table1.IndexName := 'CustID' else if ColName = 'NAME' then Table1.IndexName := 'CustNameID' else if ColName = 'TYPE' then Table1.IndexName := 'CustType' else // don't change the index for other columns end;
In all cases, it's best also to specify the index to be used when the program starts:
procedure TForm1.FormCreate(Sender: TObject); begin Table1.Open; Table1.IndexFieldNames := 'ID'; // or Table1.IndexFieldNames := DBGrid1.Fields.FieldName; // or Table1.IndexName := 'CustID'; First; end;