Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- unit laba_4_1_f1;
- interface
- uses
- Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
- Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.Grids, System.RegularExpressions,
- Vcl.ExtCtrls, Vcl.Imaging.pngimage, Data.DB, Vcl.DBGrids, Vcl.ComCtrls;
- type
- TArrStr = Array of String;
- TArrInt = Array of Integer;
- TPersonAndHisResults = Record
- FGroupNumber: String[9];
- FSurname: String[16];
- FGradeMath, FGradePhys, FGradeProgr, FGradeEngGraph: Byte;
- End;
- TArrPeopleAndResults = Array of TPersonAndHisResults;
- TBuckets = Array of TArrPeopleAndResults;
- TFormMain = class(TForm)
- MainMenu1: TMainMenu;
- N1: TMenuItem;
- N3: TMenuItem;
- OpenDialog1: TOpenDialog;
- N4: TMenuItem;
- N7: TMenuItem;
- N6: TMenuItem;
- LabelTask: TLabel;
- ButtonDelete: TButton;
- N2: TMenuItem;
- StringGrid1: TStringGrid;
- PanelRight: TPanel;
- PanelDown: TPanel;
- LabelInfoAboutPerson: TLabel;
- LabelInformation: TLabel;
- LabelToMeasureScreenOfUser: TLabel;
- CheckReadOnly: TCheckBox;
- ComboBoxSortBy: TComboBox;
- ButtonSortBy: TButton;
- ButtonFilterBy: TButton;
- ComboBoxFilterWhat: TComboBox;
- ComboBoxFilterHow: TComboBox;
- ComboBoxFilterNumber: TComboBox;
- SaveDialog1: TSaveDialog;
- N5: TMenuItem;
- N8: TMenuItem;
- ComboBoxFilterGroup: TComboBox;
- procedure N3Click(Sender: TObject);
- procedure N7Click(Sender: TObject);
- procedure N6Click(Sender: TObject);
- procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
- procedure FormCreate(Sender: TObject);
- procedure ButtonDeleteClick(Sender: TObject);
- procedure N2Click(Sender: TObject);
- procedure StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer;
- const Value: string);
- function CheckAndCorrectCell(Input: String; Column: Byte) : String;
- procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
- var CanSelect: Boolean);
- procedure LabelInfoFill(ARow: Integer);
- procedure CheckReadOnlyClick(Sender: TObject);
- procedure DeleteRow(ARow: Integer);
- procedure ButtonSortByClick(Sender: TObject);
- procedure ButtonFilterByClick(Sender: TObject);
- function MsdSort(ArrInput: TArrPeopleAndResults) : TArrPeopleAndResults;
- function SplitInputBetweenLists(ArrInput: TArrPeopleAndResults; LetterNumber: Integer; ArrBuckets: TBuckets;
- Bitness: Integer) : TBuckets;
- function FindIndexForSorting(Person : TPersonAndHisResults; LetterNumber: Integer) : Integer;
- function CountAverageScore(Person: TPersonAndHisResults) : Single;
- function LoadInfoFromGridToArray() : TArrPeopleAndResults;
- procedure RepresentDataInGrid(ArrayOfData: TArrPeopleAndResults);
- function FilterData(ArrayOfData: TArrPeopleAndResults) : TArrPeopleAndResults;
- procedure N5Click(Sender: TObject);
- procedure MoveMouseAfterFilteringToKillBug();
- procedure N8Click(Sender: TObject);
- procedure ComboBoxFilterGroupEnter(Sender: TObject);
- function MultPixels(PixQuant: Integer) : Integer;
- private
- SelectedRow: Integer;
- MultPix: Single;
- ArrOfData, ArrOfDataTemp: TArrPeopleAndResults; // Для сортировок и фильтров
- StrFile: String;
- IsSaved, WasOnlyRead: Boolean;
- GroupNumbers: TArrStr;
- public
- end;
- TGridHelper = class(TStringGrid);
- const
- LabelInfoAboutPersonCaption = 'Выберите строку в таблице, чтобы посмотреть информацию.';
- RegExForGroupNumber = '\d{1,9}';
- RegExForSurname = '[a-zA-Zа-яА-Я][-a-zA-Zа-яА-Я]{0,15}';
- RegExForGrades = '10|[1-9]';
- StrNoName = 'Безымянный';
- var
- FormMain: TFormMain;
- implementation
- {$R *.dfm}
- function FindRegEx(SInput, StrRegEx: String; StrIfNothingFound: String = '') : TArrStr; forward;
- //******************************************************************************
- // Работа с таблицей
- function TFormMain.CheckAndCorrectCell(Input: String; Column: Byte) : String;
- var
- RightString: String;
- begin
- case Column of
- 0: RightString := FindRegEx(Input, RegExForGroupNumber)[0];
- 1: RightString := FindRegEx(Input, RegExForSurname)[0];
- 2..5: RightString := FindRegEx(Input, RegExForGrades)[0];
- end;
- Result := RightString;
- end;
- procedure TFormMain.CheckReadOnlyClick(Sender: TObject);
- begin
- with StringGrid1 do
- begin
- if CheckReadOnly.Checked then
- Options := Options - [goEditing]
- else
- Options := Options + [goEditing];
- end;
- end;
- procedure TFormMain.StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer;
- const Value: string);
- var
- Input: String;
- SelStart: Integer;
- i: Integer;
- IsEmpty: Boolean;
- begin
- if ACol = 0 then
- with ComboBoxFilterGroup do
- begin
- Items.Clear;
- Items.Add('*Все группы');
- ItemIndex := 0;
- end;
- IsSaved := False;
- Input := Value;
- Input := CheckAndCorrectCell(Input, ACol);
- with TGridHelper(StringGrid1) do
- SelStart := InplaceEditor.SelStart;
- StringGrid1.Cells[Acol, ARow] := Input;
- with TGridHelper(StringGrid1) do
- InplaceEditor.SelStart := SelStart;
- LabelInfoFill(ARow);
- with StringGrid1 do
- begin
- if (ARow = RowCount - 1) then
- RowCount := RowCount + 1;
- if (ARow <> RowCount - 1) then
- begin
- IsEmpty := True;
- i := 0;
- while (i < 6) and IsEmpty do
- begin
- if Cells[i, ARow].Trim <> '' then
- IsEmpty := False;
- Inc(i);
- end;
- if IsEmpty then
- begin
- DeleteRow(ARow);
- LabelInfoFill(ARow);
- end;
- end;
- end;
- end;
- //******************************************************************************
- // Сортировка и фильтр
- procedure TFormMain.ButtonFilterByClick(Sender: TObject);
- begin
- with ButtonFilterBy do
- begin
- if Caption = 'Фильтровать' then
- begin
- Caption := 'Не фильтровать';
- ComboBoxFilterWhat.Enabled := False;
- ComboBoxFilterHow.Enabled := False;
- ComboBoxFilterNumber.Enabled := False;
- ComboBoxFilterGroup.Enabled := False;
- ButtonDelete.Enabled := False;
- SelectedRow := -1;
- with StringGrid1 do
- Options := Options - [goEditing];
- with CheckReadOnly do
- begin
- WasOnlyRead := Checked;
- Checked := True;
- Enabled := False;
- end;
- ArrOfData := LoadInfoFromGridToArray();
- ArrOfDataTemp := FilterData(ArrOfData);
- if Length(ArrOfDataTemp) > 0 then
- begin
- RepresentDataInGrid(ArrOfDataTemp);
- MoveMouseAfterFilteringToKillBug();
- DeleteRow(StringGrid1.RowCount - 1);
- SetLength(ArrOfDataTemp, 0);
- end
- else
- begin
- ShowMessage('Не найдено ни одного совпадения');
- ButtonFilterByClick(Self);
- end;
- end
- else
- begin
- Caption := 'Фильтровать';
- ComboBoxFilterWhat.Enabled := True;
- ComboBoxFilterHow.Enabled := True;
- ComboBoxFilterNumber.Enabled := True;
- ComboBoxFilterGroup.Enabled := True;
- if not WasOnlyRead then
- with StringGrid1 do
- Options := Options + [goEditing];
- with CheckReadOnly do
- begin
- Checked := WasOnlyRead;
- Enabled := True;
- end;
- RepresentDataInGrid(ArrOfData);
- end;
- end;
- end;
- procedure TFormMain.MoveMouseAfterFilteringToKillBug();
- var
- GridRect: TGridRect;
- Row: Integer;
- CursorClipArea: TRect;
- BoundsRect: TRect;
- MousePoint1, MousePoint2: TPoint;
- begin
- GetCursorPos(MousePoint1);
- GridRect := StringGrid1.Selection;
- Row := GridRect.Top;
- CursorClipArea.TopLeft := StringGrid1.ClientToScreen(StringGrid1.CellRect(0, 0).TopLeft);
- CursorClipArea.BottomRight := StringGrid1.ClientToScreen(StringGrid1.CellRect(0, 0).BottomRight);
- CursorClipArea.BottomRight.X := CursorClipArea.BottomRight.X - Round(StringGrid1.ColWidths[0] / 2);
- CursorClipArea.BottomRight.Y := CursorClipArea.BottomRight.Y - Round(StringGrid1.RowHeights[1] / 2);
- Winapi.Windows.ClipCursor(@CursorClipArea);
- GetCursorPos(MousePoint2);
- mouse_event(MOUSEEVENTF_LEFTDOWN,MousePoint2.X,MousePoint2.Y,0,0);
- mouse_event(MOUSEEVENTF_LEFTUP,MousePoint2.X,MousePoint2.Y,0,0);
- Winapi.Windows.ClipCursor(nil);
- SetCursorPos(MousePoint1.X, MousePoint1.Y);
- end;
- procedure TFormMain.ButtonSortByClick(Sender: TObject);
- var
- IsCorrect: Boolean;
- begin
- IsCorrect := True;
- if (StringGrid1.RowCount = 2) and (ButtonFilterBy.Caption = 'Фильтровать') then
- begin
- ShowMessage('Таблица пуста');
- IsCorrect := False;
- end;
- if IsCorrect then
- begin
- IsSaved := False;
- ArrOfDataTemp := LoadInfoFromGridToArray();
- ArrOfDataTemp := MsdSort(ArrOfDataTemp);
- RepresentDataInGrid(ArrOfDataTemp);
- SetLength(ArrOfDataTemp, 0);
- SelectedRow := - 1;
- LabelInfoAboutPerson.Caption := LabelInfoAboutPersonCaption;
- ButtonDelete.Enabled := False;
- end;
- end;
- function TFormMain.FilterData(ArrayOfData: TArrPeopleAndResults) : TArrPeopleAndResults;
- var
- Person: TPersonAndHisResults;
- IndexesOfFilteredPerson: TArrInt;
- WhatToCompareWith, i, k: Integer;
- WhatToFilter: Single;
- IsAllowedByFilter: Boolean;
- ArrOut: TArrPeopleAndResults;
- begin
- for i := 0 to High(ArrayOfData) do
- begin
- Person := ArrayOfData[i];
- with ComboBoxFilterGroup do
- if (ItemIndex = 0) or (Items[ItemIndex] = Person.FGroupNumber) then
- begin
- with Person do
- case ComboBoxFilterWhat.ItemIndex of
- 0: WhatToFilter := CountAverageScore(Person);
- 1: WhatToFilter := FGradeMath;
- 2: WhatToFilter := FGradePhys;
- 3: WhatToFilter := FGradeProgr;
- 4: WhatToFilter := FGradeEngGraph;
- end;
- if WhatToFilter > 0 then
- begin
- WhatToCompareWith := 10 - ComboBoxFilterNumber.ItemIndex;
- case ComboBoxFilterHow.ItemIndex of
- 0: IsAllowedByFilter := WhatToFilter >= WhatToCompareWith;
- 1: IsAllowedByFilter := WhatToFilter <= WhatToCompareWith;
- 2: IsAllowedByFilter := WhatToFilter = WhatToCompareWith;
- end;
- end
- else
- IsAllowedByFilter := False;
- end
- else
- IsAllowedByFilter := False;
- if IsAllowedByFilter then
- begin
- SetLength(IndexesOfFilteredPerson, Length(IndexesOfFilteredPerson) + 1);
- IndexesOfFilteredPerson[High(IndexesOfFilteredPerson)] := i;
- end;
- end;
- k := 0;
- SetLength(ArrOut, Length(IndexesOfFilteredPerson));
- for i in IndexesOfFilteredPerson do
- begin
- ArrOut[k] := ArrayOfData[i];
- Inc(k);
- end;
- Result := ArrOut;
- end;
- procedure TFormMain.RepresentDataInGrid(ArrayOfData: TArrPeopleAndResults);
- var
- i, OldRowCount, NewRowCount: Integer;
- begin
- with StringGrid1 do
- begin
- OldRowCount := RowCount;
- NewRowCount := Length(ArrayOfData) + 2;
- for i := OldRowCount - 2 downto NewRowCount - 1 do
- DeleteRow(Row);
- RowCount := Length(ArrayOfData) + 2;
- for i := 1 to RowCount - 2 do
- begin
- Cells[0, i] := FindRegEx(ArrayOfData[i - 1].FGroupNumber,
- RegExForGroupNumber, '')[0];
- if Cells[0, i] = '0' then
- Cells[0, i] := '';
- Cells[1, i] := FindRegEx(ArrayOfData[i - 1].FSurname, RegExForSurname, '')[0];
- Cells[2, i] := FindRegEx(IntToStr(ArrayOfData[i - 1].FGradeMath), RegExForGrades, '')[0];
- Cells[3, i] := FindRegEx(IntToStr(ArrayOfData[i - 1].FGradePhys), RegExForGrades, '')[0];
- Cells[4, i] := FindRegEx(IntToStr(ArrayOfData[i - 1].FGradeProgr), RegExForGrades, '')[0];
- Cells[5, i] := FindRegEx(IntToStr(ArrayOfData[i - 1].FGradeEngGraph), RegExForGrades, '')[0];
- end;
- end;
- end;
- function TFormMain.LoadInfoFromGridToArray() : TArrPeopleAndResults;
- var
- i, j: Integer;
- StrTemp, StrTemp2: String;
- ArrayOfData: TArrPeopleAndResults;
- begin
- with StringGrid1 do
- begin
- SetLength(ArrayOfData, RowCount - 2);
- for i := 1 to RowCount - 2 do
- begin
- StrTemp := FindRegEx(Cells[0, i], RegExForGroupNumber, '0')[0];
- if FindRegEx(StrTemp, '0+')[0] = StrTemp then
- StrTemp := '0';
- ArrayOfData[i - 1].FGroupNumber := StrTemp;
- StrTemp2 := FindRegEx(Cells[1, i], RegExForSurname, StrNoName)[0];
- if Length(StrTemp2) > 1 then
- StrTemp := Copy(StrTemp2, 2, 15)
- else
- StrTemp := '';
- ArrayOfData[i - 1].FSurname := AnsiUpperCase(StrTemp2[1]) + AnsiLowerCase(StrTemp);
- StrTemp := FindRegEx(Cells[2, i], RegExForGrades, '0')[0];
- ArrayOfData[i - 1].FGradeMath := StrToInt(StrTemp);
- StrTemp := FindRegEx(Cells[3, i], RegExForGrades, '0')[0];
- ArrayOfData[i - 1].FGradePhys := StrToInt(StrTemp);
- StrTemp := FindRegEx(Cells[4, i], RegExForGrades, '0')[0];
- ArrayOfData[i - 1].FGradeProgr := StrToInt(StrTemp);
- StrTemp := FindRegEx(Cells[5, i], RegExForGrades, '0')[0];
- ArrayOfData[i - 1].FGradeEngGraph := StrToInt(StrTemp);
- end;
- end;
- Result := ArrayOfData;
- end;
- procedure TFormMain.ComboBoxFilterGroupEnter(Sender: TObject);
- var
- i, j, TempItemIndex: Integer;
- TempItem: String;
- SameNotFound: Boolean;
- begin
- with StringGrid1 do
- begin
- SetLength(GroupNumbers, 0);
- for i := 1 to RowCount - 2 do
- begin
- SameNotFound := True;
- j := 0;
- if (Cells[0, i].Trim = '') or (StrToInt(Cells[0, i]) = 0) then
- SameNotFound := False;
- while (j < Length(GroupNumbers)) and SameNotFound do
- begin
- if Cells[0, i] = GroupNumbers[j] then
- SameNotFound := False;
- Inc(j);
- end;
- if SameNotFound then
- begin
- SetLength(GroupNumbers, Length(GroupNumbers) + 1);
- GroupNumbers[High(GroupNumbers)] := Cells[0 , i];
- end;
- end;
- end;
- with ComboBoxFilterGroup do
- begin
- TempItemIndex := ItemIndex;
- TempItem := Items[TempItemIndex];
- Items.Clear;
- Items.Add('*Все группы');
- for i := 0 to High(GroupNumbers) do
- Items.Add(GroupNumbers[i]);
- if Items[TempItemIndex] = TempItem then
- ItemIndex := TempItemIndex
- else
- ItemIndex := 0;
- end;
- end;
- function TFormMain.FindIndexForSorting(Person : TPersonAndHisResults; LetterNumber: Integer) : Integer;
- var
- Index, i, Temp: Integer;
- Ch: Char;
- ACh: AnsiChar;
- Str: String;
- AverageScore: Single;
- begin
- with ComboBoxSortBy do
- begin
- Case ItemIndex of
- 0: begin
- Str := Person.FGroupNumber;
- for i := 1 to 16 - Length(Str) do
- Str := '0' + Str;
- Ch := Str[LetterNumber];
- Index := Ord(Ch);
- if Person.FGroupNumber = '0' then
- Index := 255;
- end;
- 1: begin
- ACh := Person.FSurname[LetterNumber];
- Index := Ord(ACh);
- if (FindRegEx(Person.FSurname, StrNoName, '')[0] <> '') and (LetterNumber < 2) then
- Index := 255;
- end;
- 2..3: begin
- AverageScore := CountAverageScore(Person);
- Str := FloatToStrF(AverageScore, ffFixed, 2, 2);
- if Length(Str) < 5 then
- Str := '0' + Str;
- for i := 1 to 16 - Length(Str) do
- Str := Str + '0';
- Temp := Ord(Str[LetterNumber]);
- if AverageScore = 0 then
- Temp := 255;
- end;
- End;
- Case ItemIndex of
- 2: begin
- Index := 255 - Temp;
- if Temp = 255 then
- Index := 255;
- end;
- 3: Index := Temp;
- end;
- end;
- Result := Index;
- end;
- function TFormMain.CountAverageScore(Person: TPersonAndHisResults) : Single;
- var
- AverageScore: Single;
- Divider: Byte;
- begin
- AverageScore := 0;
- Divider := 0;
- with Person do
- begin
- if FGradeMath > 0 then
- Inc(Divider);
- if FGradePhys > 0 then
- Inc(Divider);
- if FGradeProgr > 0 then
- Inc(Divider);
- if FGradeEngGraph > 0 then
- Inc(Divider);
- if Divider > 0 then
- AverageScore := (FGradeMath + FGradePhys + FGradeProgr + FGradeEngGraph) / Divider;
- end;
- Result := AverageScore;
- end;
- function TFormMain.SplitInputBetweenLists(ArrInput: TArrPeopleAndResults; LetterNumber: Integer; ArrBuckets: TBuckets;
- Bitness: Integer): TBuckets;
- var
- Index, j, i: Integer;
- iInBuckets: Array of Integer;
- Person: TPersonAndHisResults;
- Ch: AnsiChar;
- Bucket: TArrPeopleAndResults;
- ArrBuckets2: TBuckets;
- begin
- SetLength(ArrBuckets2, Bitness);
- for i := 0 to High(ArrBuckets2) do
- Setlength(ArrBuckets2[i], 0);
- for Person in ArrInput do
- begin
- Index := FindIndexForSorting(Person, LetterNumber);
- SetLength(ArrBuckets[Index], Length(ArrBuckets[Index]) + 1);
- ArrBuckets[Index][High(ArrBuckets[Index])] := Person;
- end;
- if LetterNumber < 16 then
- begin
- Inc(LetterNumber);
- for Bucket in ArrBuckets do
- begin
- i := 0;
- if Length(Bucket) <> 0 then
- begin
- ArrBuckets2 := SplitInputBetweenLists(Bucket, LetterNumber, ArrBuckets2, Bitness);
- for j := 0 to Bitness - 1 do
- begin
- for Person in ArrBuckets2[j] do
- begin
- Bucket[i] := Person;
- Inc(i);
- end;
- Setlength(ArrBuckets2[j], 0);
- end;
- end;
- end;
- end;
- Result := ArrBuckets;
- end;
- function TFormMain.MsdSort(ArrInput: TArrPeopleAndResults) : TArrPeopleAndResults;
- const
- Bitness = 256; // разрядность
- var
- i, j, LetterNumber: Integer;
- ArrBuckets: TBuckets;
- Person: TPersonAndHisResults;
- Begin
- SetLength(ArrBuckets, Bitness);
- for i := 0 to High(ArrBuckets) do
- Setlength(ArrBuckets[i], 0);
- LetterNumber := 1;
- ArrBuckets := SplitInputBetweenLists(ArrInput, LetterNumber, ArrBuckets, Bitness);
- // moving lists back into input array
- i := 0;
- for j := 0 to Bitness - 1 do
- begin
- for Person in ArrBuckets[j] do
- begin
- ArrInput[i] := Person;
- Inc(i);
- end;
- Setlength(ArrBuckets[j], 0); //clear ArrBuckets
- end;
- Result := ArrInput;
- end;
- //******************************************************************************
- // Удаление данных, а также информационное окно
- procedure TFormMain.ButtonDeleteClick(Sender: TObject);
- var
- Bool: Boolean;
- begin
- if (SelectedRow <> StringGrid1.RowCount - 1) and (MessageDlg(
- 'Вы уверены, что хотите удалить этого студента?',
- mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
- begin
- DeleteRow(SelectedRow);
- if SelectedRow <> StringGrid1.RowCount - 1 then
- begin
- Bool := True;
- StringGrid1SelectCell(Self, 0, SelectedRow, Bool);
- end
- else
- begin
- SelectedRow := -1;
- LabelInfoAboutPerson.Caption := LabelInfoAboutPersonCaption;
- ButtonDelete.Enabled := False;
- end;
- end;
- end;
- procedure TFormMain.StringGrid1SelectCell(Sender: TObject; ACol,
- ARow: Integer; var CanSelect: Boolean);
- begin
- SelectedRow := ARow;
- LabelInfoFill(ARow);
- if (ButtonFilterBy.Caption = 'Фильтровать') and (SelectedRow <> StringGrid1.RowCount - 1) then
- ButtonDelete.Enabled := True
- else
- ButtonDelete.Enabled := False;
- end;
- procedure TFormMain.LabelInfoFill(ARow: Integer);
- begin
- With StringGrid1 do
- begin
- LabelInfoAboutPerson.Caption := 'Группа: ' + Cells[0, ARow] + #10#13 +
- 'Фамилия: ' + Cells[1, ARow] + #10#13 + #10#13 +
- 'Оценки:' + #10#13 +
- ' Математика: ' + Cells[2, ARow] + #10#13 +
- ' Физика: ' + Cells[3, ARow] + #10#13 +
- ' Программирование: ' + Cells[4, ARow] + #10#13 +
- ' Инженерная графика: ' + Cells[5, ARow] + #10#13;
- end;
- end;
- procedure TFormMain.DeleteRow(ARow: Integer);
- var
- i, j: Integer;
- begin
- IsSaved := False;
- with StringGrid1 do
- begin
- for i := ARow + 1 to RowCount - 1 do
- for j := 0 to ColCount - 1 do
- Cells[j, i - 1] := Cells[j, i];
- for i := 0 to ColCount - 1 do
- Cells[i, RowCount-1] := '';
- RowCount := RowCount - 1;
- end;
- end;
- //******************************************************************************
- // Работа с файлами
- procedure TFormMain.N7Click(Sender: TObject);
- const
- ErrorDuringInputOccured = 'Возникла ошибка при открытии файла.' + #10#13 +
- 'Пожалуйста, выберите файл нужного формата(.datgrad) с ' +
- 'корректными данными.';
- var
- FileInput : File of TPersonAndHisResults;
- i, FirstTimeSeconds, NewTimeSeconds: Integer;
- PathToFile: String;
- IsNotTooLong: Boolean;
- begin
- if not IsSaved and (MessageDlg('Вы хотите сохранить текущие данные?' +
- #10#13 + 'Иначе после открытия файла текущие записи будут удалены.',
- mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
- N5Click(Self);
- if (IsSaved or (MessageDlg('Вы уверены, что хотите открыть другой файл?' + #10#13 +
- 'Все текущие записи будут удалены.', mtConfirmation, [mbYes, mbCancel], 0) = mrYes))
- and OpenDialog1.Execute then
- begin
- if ButtonFilterBy.Caption <> 'Фильтровать' then
- ButtonFilterByClick(Self);
- PathToFile := OpenDialog1.FileName;
- try
- AssignFile(FileInput, PathToFile);
- Reset(FileInput);
- FirstTimeSeconds := StrToInt(Copy(TimeToStr(Time), 7, 2));
- IsNotTooLong := True;
- SetLength(ArrOfData, FileSize(FileInput));
- i := 0;
- while (not Eof(FileInput) and IsNotTooLong) do
- begin
- Read(FileInput, ArrOfData[i]);
- Inc(i);
- NewTimeSeconds := StrToInt(Copy(TimeToStr(Time), 7, 2));
- IsNotTooLong := (Abs(NewTimeSeconds - FirstTimeSeconds) < 2) or (NewTimeSeconds < 2);
- end;
- CloseFile(FileInput);
- if IsNotTooLong then
- begin
- StrFile := PathToFile;
- N5.Enabled := True;
- RepresentDataInGrid(ArrOfData);
- IsSaved := True;
- end
- else
- ShowMessage(ErrorDuringInputOccured);
- except
- ShowMessage(ErrorDuringInputOccured);
- end;
- SelectedRow := -1;
- LabelInfoAboutPerson.Caption := LabelInfoAboutPersonCaption;
- ButtonDelete.Enabled := False;
- CheckReadOnly.Checked := True;
- with StringGrid1 do
- Options := Options - [goEditing]
- end;
- end;
- procedure TFormMain.N6Click(Sender: TObject);
- var
- FileOutput : File of TPersonAndHisResults;
- i: Integer;
- StrFilePath: String;
- Person: TPersonAndHisResults;
- ShouldNotRepeat: Boolean;
- begin
- if (StringGrid1.RowCount > 2) and (ButtonFilterBy.Caption = 'Фильтровать') then
- try
- repeat
- ShouldNotRepeat := True;
- if SaveDialog1.Execute then
- begin
- StrFilePath := SaveDialog1.FileName;
- StrFilePath := FindRegEx(StrFilePath, '.+\.datgrad', StrFilePath + '.datgrad')[0];
- StrFile := StrFilePath;
- N5.Enabled := True;
- if FileExists(StrFilePath) then
- if MessageDlg('Такой файл уже существует.' +
- #10#13 + 'Вы хотите перезаписать файл? Это действие невозможно отменить.',
- mtConfirmation, [mbYes, mbNo], 0) = mrYes then
- ShouldNotRepeat := True
- else
- ShouldNotRepeat := False
- else
- ShouldNotRepeat := True;
- if ShouldNotRepeat then
- begin
- AssignFile(FileOutput, StrFilePath);
- Rewrite(FileOutput);
- ArrOfData := LoadInfoFromGridToArray;
- for Person in ArrOfData do
- Write(FileOutput, Person);
- CloseFile(FileOutput);
- IsSaved := True;
- end;
- end;
- until ShouldNotRepeat;
- except
- ShowMessage('Не удается открыть файл для вывода данных или записать в него данные.');
- end
- else
- ShowMessage('Нет данных для экспорта или включен фильтр.');
- end;
- procedure TFormMain.N5Click(Sender: TObject);
- var
- FileOutput : File of TPersonAndHisResults;
- Person: TPersonAndHisResults;
- begin
- if MessageDlg('Вы хотите перезаписать файл "' + StrFile + '"?' + #10#13 +
- 'Это действие невозможно отменить.', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
- if FileExists(StrFile) then
- if (StringGrid1.RowCount > 2) and (ButtonFilterBy.Caption = 'Фильтровать') then
- begin
- AssignFile(FileOutput, StrFile);
- Rewrite(FileOutput);
- ArrOfData := LoadInfoFromGridToArray;
- for Person in ArrOfData do
- Write(FileOutput, Person);
- CloseFile(FileOutput);
- IsSaved := True;
- end
- else
- ShowMessage('Нет данных для экспорта или включен фильтр.')
- else
- begin
- ShowMessage('Этого файла уже не существует.');
- StrFile := '';
- N5.Enabled := False;
- N6Click(Self);
- end;
- end;
- //******************************************************************************
- // Form Create
- procedure TFormMain.FormCreate(Sender: TObject);
- var
- i: Integer;
- begin
- MultPix := LabelToMeasureScreenOfUser.Width / 100;
- LabelTask.Caption := 'Сведения о результатах комплексной контрольной.';
- LabelInfoAboutPerson.Caption := LabelInfoAboutPersonCaption;
- SelectedRow := -1;
- StrFile := '';
- IsSaved := True;
- with StringGrid1 do
- begin
- RowCount := 2;
- ColCount := 6;
- Cells[0, 0] := 'Группа №';
- Cells[1, 0] := 'Фамилия';
- Cells[2, 0] := 'Матем';
- Cells[3, 0] := 'Физика';
- Cells[4, 0] := 'Прогр';
- Cells[5, 0] := 'ИнжГр';
- for i := 2 to 5 do
- ColWidths[i] := MultPixels(58);
- ColWidths[0] := MultPixels(100);
- ColWidths[1] := MultPixels(120);
- end;
- end;
- //******************************************************************************
- // Прочее
- procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
- begin
- CanClose := IsSaved or (StringGrid1.RowCount = 2) or (MessageDlg('Вы уверены, что хотите выйти из программы?' +
- #10#13 + 'Все несохранённые данные будут утеряны.',
- mtConfirmation, [mbYes, mbNo], 0) = mrYes);
- end;
- procedure TFormMain.N2Click(Sender: TObject);
- begin
- ShowMessage('Помощь' + #10#13 +
- 'Вы можете просматривать базу данных, изменять её компоненты, добавлять и удалять строки.' +
- #10#13 + 'Вы также можете сортировать и фильровать данные.' + #10#13#10#13 +
- ' - Чтобы открыть базу данных из файла, нажмите "Открыть" в Меню.' + #10#13 +
- ' - Чтобы получить возможность изменять данные, уберите галочку "Только чтение".' + #10#13 +
- ' - Чтобы добавить новую информацию, используйте последнюю строку таблицы.' + #10#13 +
- ' - Чтобы удалить строку, сотрите с неё данные либо нажмите кнопку "Удалить" после того, как выберите строку для удаления.' + #10#13 +
- ' - Чтобы экспортировать данные, нажмите "Сохранить как..." в Меню.' + #10#13 +
- ' - Вы также можете нажать "Сохранить", чтобы сохранить данные в последний открытый файл.' + #10#13 +
- ' - Чтобы отсортировать данные, выберите, по какому критерию сортировать, затем нажмите кнопку "Сортировать".' + #10#13 +
- ' - Чтобы фильтровать данные, выберите, что, как и относительно чего фильтроваь, затем нажмите кнопку "Фильтровать".');
- end;
- procedure TFormMain.N3Click(Sender: TObject);
- begin
- ShowMessage('Панев Александр, гр. 051007' + #10#13 + 'Минск, 2021');
- end;
- procedure TFormMain.N8Click(Sender: TObject);
- begin
- ShowMessage('Вывести список студентов группы Х в алфавитном порядке ' +
- 'фамилий, у которых средний балл за контрольную 7 и выше.');
- end;
- function FindRegEx(SInput, StrRegEx: String; StrIfNothingFound: String = '') : TArrStr;
- var
- ArrStr: TArrStr;
- RegEx: TRegEx;
- MatchCollection: TMatchCollection;
- i: Integer;
- begin
- RegEx := TRegEx.Create(StrRegEx);
- MatchCollection := RegEx.Matches(SInput);
- SetLength(ArrStr, MatchCollection.Count);
- for i := 0 to MatchCollection.Count - 1 do
- ArrStr[i] := MatchCollection.Item[i].Value;
- if (Length(ArrStr) < 1) then
- ArrStr := [StrIfNothingFound];
- Result := ArrStr;
- end;
- function TFormMain.MultPixels(PixQuant: Integer) : Integer;
- begin
- Result := Round(PixQuant * MultPix);
- end;
- end.
Advertisement
Add Comment
Please, Sign In to add comment