Делфи как найти да нет

Ну, здесь в первую очередь, желание продемонстрировать функцию MessageBox(), а стиль кода каждый сам для себя определяет. Я, например, привык все условия заключать в скобки…

– KiTE

3 июн 2012 в 14:42

I’m trying to replace True/False with Yes/No in a DBGrid. The code below almost works:

procedure TDatamodule1.DBGridDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);

  var
    sText : String;

begin
  if (UpperCase(Column.Field.FieldName) = UpperCase('Approved')) or
     (UpperCase(Column.Field.FieldName) = UpperCase('Obsolete')) then
    begin
      if Column.Field.Value = True then
        sText := 'Yes'
      Else
        If Column.Field.Value = False Then
          sText := 'No'
        Else
          sText := '';
      (Sender as TDBGrid).Canvas.FillRect(Rect);
      (Sender as TDBGrid).Canvas.TextRect(Rect, Rect.Left+3, Rect.Top+2, sText);
    end;
end;

This appeared to work until I started using the keyboard cursor keys to move around the grid. The cell that has the focus always has both True and Yes or False and No drawn on top of each other. How do I prevent the default True/False label from being drawn on the cell that has focus? All other cells of the grid are perfect.

Edit: I failed to mention that the grid is set to Readonly and I’ve noticed the problem is with both selected and focused.
Thanks in advance.

asked Sep 10, 2013 at 0:41

Mike's user avatar

MikeMike

1533 silver badges11 bronze badges

2

A simple solution would be to set your Boolean field DisplayValues:

MyField.DisplayValues := 'Yes;No';

answered Sep 10, 2013 at 9:35

kobik's user avatar

kobikkobik

21k4 gold badges61 silver badges120 bronze badges

One way to achieve this is to set an OnGetText event handler for these fields. If you have static fields you can set those during design time. With dynamic fields you can do so in the FormCreate event.

procedure TMyForm.MyFieldGetText(Sender: TField; var Text: string; DisplayText: Boolean);
begin
  if Sender.AsBoolean then
    Text := 'Yes'
  else
    Text := 'No';
end;

answered Sep 10, 2013 at 6:52

Uwe Raabe's user avatar

Uwe RaabeUwe Raabe

44.7k3 gold badges81 silver badges129 bronze badges

1

I would say that you’re working at the wrong level of abstraction.
Use two calculated columns (AFlag and OFlag in the example below) and define an OnCalcFields event for your clientdataset. The below code is attached to a dataset called ‘qCpap’.

procedure TView.qCpapCalcFields(DataSet: TDataSet);
begin
 if qCpapApproved.AsBoolean 
  then qCpapAFlag.AsString:= 'Yes'
  else qCpapAFlag.AsString:= 'No';

 if qCpapObsolete.AsBoolean 
  then qCpapOFlag.AsString:= 'Yes'
  else qCpapOFlag.AsString:= 'No';
end;

Incidentally, there’s no point in using the ‘uppercase’ function on a string constant: you may as well write the string in uppercase yourself.

answered Sep 10, 2013 at 3:00

No'am Newman's user avatar

No’am NewmanNo’am Newman

6,3405 gold badges37 silver badges50 bronze badges

2

I resolved my issue with a lot of trial and error. First, in the DBGrid components I set dgEditing to false as it was unnecessary (my grid is readonly). This prevents the user from getting the cell into the focused mode. Second, I set DefaultDrawing to False. I updated my DBGridDrawColumnCell procedure as follows:

procedure TDatamodule1.DBGridDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);

  var
    sText : String;

begin
  if gdselected in state then { set proper colors if cell is selected }
    Begin
      (Sender as TDBGrid).Canvas.Font.Color := 
        TStyleManager.ActiveStyle.GetSystemColor(clwindowtext);
      (Sender as TDBGrid).Canvas.Brush.Color := 
        TStyleManager.ActiveStyle.GetSystemColor(clhighlight);
    End;

  if (UpperCase(Column.Field.FieldName) = 'APPROVED') or
     (UpperCase(Column.Field.FieldName) = 'OBSOLETE')) then
    begin
      if Column.Field.Value = True then
        sText := 'Yes'
      Else
        If Column.Field.Value = False Then
          sText := 'No'
        Else
          sText := '';
      (Sender as TDBGrid).Canvas.FillRect(Rect);
      (Sender as TDBGrid).Canvas.TextRect(Rect, Rect.Left+3, Rect.Top+2, sText);
    end
  Else
    Begin { I added this to draw all other columns as defaultdrawing is off }
      (Sender as TDBGrid).defaultdrawcolumncell(Rect, DataCol, Column, State);
    End;
end;

answered Sep 10, 2013 at 5:12

Mike's user avatar

MikeMike

1533 silver badges11 bronze badges

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    >
    Отображение логического поля

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    02.08.09, 08:41

      Full Member

      ***

      Рейтинг (т): 1

      В таблице Access имеется поле — тип которого «логический» (Да/Нет). Ну так вот, после связи, содержимое поля отображается в DBGrid, как True или False.
      Access:
      Поле
      Да
      Да
      Нет
      Да
      Delphi:
      True
      True
      False
      True

      Как сделать, что бы содержимое отображалось: в место True — Да, а в место False — Нет. А еще лучше будет, если поле будет иметь вид как в Accesse, вместо True/False и Да/Нет, поле с галочкой если (Да/True) и без галочки если (Нет/False).

      Сообщение отредактировано: ~WARlock~ — 02.08.09, 08:43

      Master

      ViktorXP



      Сообщ.
      #2

      ,
      02.08.09, 09:07

        в компоненте TADOTable (или TADOQuery) в нужной колонке делаешь настройки DisplayValues = ‘Да;Нет’


        Игорь Акопян



        Сообщ.
        #3

        ,
        03.08.09, 11:17

          DBGridEh умеет казать галки на логические поля :)


          vladimir74



          Сообщ.
          #4

          ,
          03.08.09, 11:25

            Цитата Игорь Акопян @ 03.08.09, 11:17

            DBGridEh умеет казать галки на логические поля :)

            ага только если мне не изменяет память, то если = null он пишет знак вопроса… Или я его с кем то путаю?


            Павел Калугин



            Сообщ.
            #5

            ,
            03.08.09, 11:29

              Читать на Королевстве, Разноцветный DBGrid для начала. http://www.delphikingdom.com/asp/viewitem.asp?catalogid=168

              Добавлено 03.08.09, 11:34
              В дополнение это
              http://www.delphikingdom.com/asp/viewitem.asp?catalogid=1193
              http://www.delphikingdom.com/asp/viewitem.asp?catalogid=667

              Wizard

              Bas



              Сообщ.
              #6

              ,
              03.08.09, 12:12


                ~WARlock~



                Сообщ.
                #7

                ,
                04.08.09, 05:52

                  Full Member

                  ***

                  Рейтинг (т): 1

                  Paul_K — благодарю за инфу.

                  Не запускается из-за ошибки.

                  Выделяю DBGrid, перехожу на поле «Событие», затем в OnDrawColumnCell прописываю код, который показан в примере:э

                  ExpandedWrap disabled

                    Var

                    Style:Integer;

                    begin

                        if Column.FieldName = ‘Кол-во’ then

                        if Column.Field.AsInteger > 0 then

                        Style := DFCS_CHECKED

                        else

                        Style := DFCS_BUTTONCHECK;

                        end;

                        DrawFrameControl(TDBGrid(Sender).Canvas.Handle, Rect, DFC_BUTTON, Style); // в этой строке ошибка

                    end;

                  Ошибка — Declaration expected but identifier ‘DrawFrameControl’ found


                  Павел Калугин



                  Сообщ.
                  #8

                  ,
                  04.08.09, 06:29

                    Обратите внимание что пример в статье писан, если мне не изменяет память в пятой версии Delphi. Надо смотриеть что в Вашей версии соответствует этой функции. Опяить же надо обратить внимание на текс чуть ниже примера:

                    Цитата

                    Функция DrawFrameControl рисует на канве в определенном прямоугольнике стандартный windows-control, тип и состояние которого определяется передаваемыми параметрами.

                    ExpandedWrap disabled

                      BOOL DrawFrameControl(

                          HDC hdc,    // handle to device context

                          LPRECT lprc,    // pointer to bounding rectangle

                          UINT uType, // frame-control type

                          UINT uState // frame-control state

                         );

                    Подробнее о том, что еще может рисовать эта функция, смотрите help по Windows API (или MSDN или win32.hlp в поставке Delphi) .

                    Добавлено 04.08.09, 06:30
                    Вполне возможно, что данная функция устарела и есть ее аналог.

                    Сообщение отредактировано: Paul_K — 04.08.09, 06:30


                    ~WARlock~



                    Сообщ.
                    #9

                    ,
                    04.08.09, 07:16

                      Full Member

                      ***

                      Рейтинг (т): 1

                      У меня Delphi 7.
                      Как быть в этой ситуации?


                      Павел Калугин



                      Сообщ.
                      #10

                      ,
                      04.08.09, 07:42

                        Почитать что написано в win32.hlp
                        Наверняка надо в USES подключить соответствующий модуль.
                        Может быть этот модуль даже название WinAPI имеет, а может и нет. сам посмотреть сейчас не имею возможности.

                        Сообщение отредактировано: Paul_K — 04.08.09, 07:44


                        ~WARlock~



                        Сообщ.
                        #11

                        ,
                        04.08.09, 08:42

                          Full Member

                          ***

                          Рейтинг (т): 1

                          А без подключения модулей можно сделать, поле с галочками?


                          vladimir74



                          Сообщ.
                          #12

                          ,
                          04.08.09, 08:57

                            это зависит от компонента, если создатель его подумал за тебя то можно…
                            как уже сказали…

                            Цитата Игорь Акопян @ 03.08.09, 11:17

                            DBGridEh умеет казать галки на логические поля :)


                            Игорь Акопян



                            Сообщ.
                            #13

                            ,
                            04.08.09, 09:23

                              Цитата vladimir74 @ 03.08.09, 11:25

                              если = null он пишет знак вопроса

                              врядли, скорее серый чекбокс состояние unknown. Что, кстати, логично ;)

                              0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                              0 пользователей:

                              • Предыдущая тема
                              • Delphi: Базы данных
                              • Следующая тема

                              Рейтинг@Mail.ru

                              [ Script execution time: 0,0702 ]   [ 16 queries used ]   [ Generated: 29.05.23, 05:30 GMT ]  

                              Понравилась статья? Поделить с друзьями:

                              Не пропустите также:

                            • Как найти центральный угол через хорду
                            • Как найти участников великой отечественной войны сайт
                            • Как найти инн по паспорту в налоговой
                            • Как найти световой поток одной лампы
                            • Как найти трисс в каэр морхен

                            • 0 0 голоса
                              Рейтинг статьи
                              Подписаться
                              Уведомить о
                              guest

                              0 комментариев
                              Старые
                              Новые Популярные
                              Межтекстовые Отзывы
                              Посмотреть все комментарии