Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Kursovaya_SVP.doc
Скачиваний:
11
Добавлен:
24.09.2019
Размер:
439.3 Кб
Скачать

4.3 Форма просмотра анкет Infoform

На рисунке 4 представлена данная форма.

Для работы с базой SQL на форме располагаются элементы DataSource1: TDataSource, ADO: TADOQuery, DBGrid1: TDBGrid.

При создании данной формы происходит заполнение 1 столбца InfoGrid:TstringGrid и подсчет количества анкет. Количество анкет оображается в Label2.

Для осуществления перехода к определенной анкете,при нажатии кнопки Button1,происходит перемещение по таблице до нужной анкеты и данные выводятся в InfoGrid при помощи процедуры SelectInfo.

Если был введен ID несуществующей анкеты,появится окно предупреждающее об этом и окно ввода ID будет очищено.

При нажатии на кнопку «Предыдущая» происходит переход к предыдущей анкете,которая будет показана в InfoGrid.

При нажатии на кнопку «Следующая» происходит переход к следующей анкете,которая будет показана в InfoGrid.

Рисунок 4 – Форма просмотра анкет.

Заключение

В ходе курсовой работы было разработано приложение, позволяющее заносить данные анкетирования в базу данных MS SQL. Также была подробно рассмотрена реализация приложения

Список используемой литературы

  1. Программирование в Delphi. Учебник по классическим теориям Delphi. – ООО «Бином-Пресс» 2006г.

  2. Разработка клиент-серверных приложений в Delphi А. Шкрыль БХВ-Петербург 2006г

3. SQL: Полное руководство Джеймс Р. Грофф, Пол Н. Вайнберг Издательство: Ирина, Издательская группа BHV, McGraw-Hill Companies 2001г.

Приложение а (обязательное)

Листинг программы

program Anketa;

uses

Forms,

MainForm in 'MainForm.pas' {Form1},

Unit1 in 'Unit1.pas' {AboutForm},

Unit2 in 'Unit2.pas' {InfoForm};

{$R *.res}

begin

Application.Initialize;

Application.Title := 'Анкета';

Application.CreateForm(TForm1, Form1);

Application.CreateForm(TAboutForm, AboutForm);

Application.Run;

end.

unit MainForm;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, Grids, DBGrids, DB, ADODB,

ExtCtrls, ComCtrls, Menus, Vcl.XPMan;

type

TForm1 = class(TForm)

DataSource1: TDataSource;

ADO: TADOQuery;

DBGrid1: TDBGrid;

SaveButton: TButton;

Label2: TLabel;

Label3: TLabel;

Label4: TLabel;

NameEdit: TEdit;

LNameEdit: TEdit;

MNameEdit: TEdit;

PolGroup: TRadioGroup;

Bdata: TLabeledEdit;

Professia: TLabeledEdit;

TimeGameL: TLabel;

TimeGameBox: TComboBox;

OpitGameL: TLabel;

OpitGameBox: TComboBox;

PlatformerL: TLabel;

PlatformerBox: TComboBox;

ConfigPCEdit: TRichEdit;

ConfigPCL: TLabel;

Game: TLabeledEdit;

GameInfoEdit: TRichEdit;

GameInfoL: TLabel;

DonatBox: TComboBox;

DonatL: TLabel;

FilmEdit: TLabeledEdit;

InfoEdit: TRichEdit;

Info: TLabel;

OsL: TLabel;

OSBox: TComboBox;

GanrGame: TLabeledEdit;

Panel1: TPanel;

PristavkaGroup: TRadioGroup;

Panel2: TPanel;

Panel3: TPanel;

Panel4: TPanel;

PriorButton: TButton;

NextButton: TButton;

MainMenu1: TMainMenu;

Af1: TMenuItem;

N1: TMenuItem;

N2: TMenuItem;

N3: TMenuItem;

N4: TMenuItem;

N5: TMenuItem;

procedure PriorButtonClick(Sender: TObject);

procedure NextButtonClick(Sender: TObject);

procedure FormCreate(Sender: TObject);

procedure SaveButtonClick(Sender: TObject);

procedure BdataKeyPress(Sender: TObject; var Key: Char);

procedure N5Click(Sender: TObject);

procedure N1Click(Sender: TObject);

procedure N3Click(Sender: TObject);

procedure N2Click(Sender: TObject);

private

{ Private declarations }

public

id: integer;

end;

var

Form1: TForm1;

l:integer; //номер активной панели

povtorSave:boolean;

implementation

uses Unit1, Unit2;

{$R *.dfm}

function definitionId: integer;//возвращает значение следующего ID анкеты

begin

Form1.ado.SQL.Clear;

Form1.ado.SQL.Text:='select id from table_1 ORDER BY id ASC;';

Form1.ado.open;

Form1.ado.Last;

try

result:=Form1.ado.Fields[0].value+1;

except result:=1;

end;

end;

procedure NewANKETA;

begin

Form1.FormCreate(Form1);

with Form1 do

begin

NameEdit.Clear;

lNameEdit.Clear;

mNameEdit.Clear;

PolGroup.ItemIndex:=-1;

professia.Clear;

Bdata.Clear;

GanrGame.Clear;

TimeGamebox.ItemIndex:=-1;

OpitGamebox.ItemIndex:=-1;

Donatbox.ItemIndex:=-1;

Platformerbox.ItemIndex:=-1;

PristavkaGroup.ItemIndex:=-1;

Osbox.ItemIndex:=-1;

Game.Clear;

FilmEdit.Clear;

ConfigPCEdit.Clear;

GameInfoEdit.Clear;

InfoEdit.Clear;

Form1.NextButton.Visible:=true;

form1.savebutton.Enabled:=false;

end;

end;

procedure Smena(l:integer);

begin

case l of

1: begin

Form1.Panel1.Visible:=true;

Form1.Panel2.Visible:=false;

Form1.Panel3.Visible:=false;

Form1.Panel4.Visible:=false;

Form1.PriorButton.Visible:=false;

Form1.NextButton.Visible:=true;

end;

2: begin

Form1.Panel1.Visible:=false;

Form1.Panel2.Visible:=true;

Form1.Panel3.Visible:=false;

Form1.Panel4.Visible:=false;

Form1.PriorButton.Visible:=true;

Form1.NextButton.Visible:=true;

end;

3: begin

Form1.Panel1.Visible:=false;

Form1.Panel2.Visible:=false;

Form1.Panel3.Visible:=true;

Form1.Panel4.Visible:=false;

Form1.PriorButton.Visible:=true;

Form1.NextButton.Visible:=true;

end;

4: begin

Form1.Panel1.Visible:=false;

Form1.Panel2.Visible:=false;

Form1.Panel3.Visible:=false;

Form1.Panel4.Visible:=true;

Form1.PriorButton.Visible:=true;

Form1.NextButton.Visible:=false;

form1.savebutton.Enabled:=true;

end;

end;

end;

procedure TForm1.PriorButtonClick(Sender: TObject);

begin

if l>1 then l:=l-1;

smena(l);

end;

procedure TForm1.NextButtonClick(Sender: TObject);

var

error:boolean;

begin

error:=false;

if l<4 then l:=l+1;

case l of

2: begin

if Polgroup.ItemIndex=-1 then begin ShowMessage('Вы не указали пол!'); error:=true; end;

try

StrToDateTime(Bdata.Text);

except

messagebox(0,'Неверный формат даты!'+#13#10+'Пример правильного ввода '+#13#10+ '01.01.2012' ,'Неверная дата',MB_Ok or MB_ICONERROR);

error:=true;

Bdata.Clear;

end;

if error then l:=1;

end;

3:begin

if TimeGamebox.ItemIndex=-1 then begin ShowMessage('Вы не указали сколько времени тратите на игры!'); error:=true; end;

if OpitGamebox.ItemIndex=-1 then begin ShowMessage('Вы не указали как вы оцениваете свой игровой опыт!'); error:=true; end;

if Platformerbox.ItemIndex=-1 then begin ShowMessage('Вы не указали как относитесь к платформерам!'); error:=true; end;

if Pristavkagroup.ItemIndex=-1 then begin ShowMessage('Вы не указали есть ли у вас приставка!');error:=true; end;

if error then l:=2;

end;

4:begin

if Osbox.ItemIndex=-1 then begin ShowMessage('Вы не указали свою ОС!'); error:=true; end;

if error then l:=3;

end;

end;

if Not error then smena(l);

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

Panel1.Visible:=true;

Panel2.Visible:=false;

Panel3.Visible:=false;

Panel4.Visible:=false;

PriorButton.Visible:=false;

povtorSave:=false;

l:=1;

form1.savebutton.Enabled:=false;

end;

procedure TForm1.SaveButtonClick(Sender: TObject);

var

error: boolean;

begin

error:=false;

if Donatbox.ItemIndex=-1 then begin ShowMessage('Вы не указали тратите ли вы деньги на игры'); error:=true; end;

if (povtorSave)and(messagebox(0,'Возможно вы пытаетесь сохранить уже существующие данные!'+#13#10+'В этом случае они будут сохранены под новым номером! Продолжить?','Повторное сохранение',MB_YesNo or MB_ICONINFORMATION)=mrNo) then error:=true;

if (not error) then begin

try

id:=DefinitionId;

ado.SQL.Text:='insert into table_1 (ID, name, fam,otch,pol,datar,professia,TimeGame,OpitGame, GanrGame, Platformer, OS, ConfigPC, Pristavka, Game, GameInfo, Donat, Film, Info)';

ado.SQL.add(' values (:ID, :name, :fam,:otch,:pol,:datar,:professia,:TimeGame,:OpitGame, :GanrGame, :Platformer, :OS, :ConfigPC, :Pristavka, :Game, :GameInfo, :Donat, :Film, :Info)');

ado.Parameters.ParamByName('name').value:=NameEdit.Text;

ado.Parameters.ParamByName('fam').value:=lNameEdit.Text;

ado.Parameters.ParamByName('otch').value:=mNameEdit.Text;

ado.Parameters.ParamByName('pol').value:=PolGroup.ItemIndex;

ado.Parameters.ParamByName('professia').value:=professia.Text;

ado.Parameters.ParamByName('DataR').value:=formatdatetime('yyyy/mm/dd',StrToDateTime(Bdata.Text));

ado.Parameters.ParamByName('GanrGame').value:=GanrGame.Text;

ado.Parameters.ParamByName('TimeGame').value:=TimeGamebox.ItemIndex;

ado.Parameters.ParamByName('OpitGame').value:=OpitGamebox.ItemIndex;

ado.Parameters.ParamByName('Donat').value:=Donatbox.ItemIndex;

ado.Parameters.ParamByName('Platformer').value:=Platformerbox.ItemIndex;

ado.Parameters.ParamByName('Pristavka').value:=PristavkaGroup.ItemIndex;

ado.Parameters.ParamByName('OS').value:=OSBox.items[Osbox.ItemIndex];

ado.Parameters.ParamByName('Game').value:=Game.Text;

ado.Parameters.ParamByName('film').value:=FilmEdit.Text;

ado.Parameters.ParamByName('ConfigPC').value:=ConfigPCEdit.Text;

ado.Parameters.ParamByName('GameInfo').value:=GameInfoEdit.Text;

ado.Parameters.ParamByName('info').value:=InfoEdit.Text;

ado.Parameters.ParamByName('id').value:=id;

ado.ExecSQL; povtorSave:=true;

messagebox(0,'Данные успешно сохранены!','Сохранение',MB_Ok or MB_ICONINFORMATION);

except

ShowMessage('Ошибка при записи данных!');

end;

end else messagebox(0,'Данные не сохранены','Сохранение',MB_Ok or MB_ICONERROR);

end;

procedure TForm1.BdataKeyPress(Sender: TObject; var Key: Char);

const

abc: set of char=['0'..'9',#8,'.'];

begin

if (not(key in abc)) then key:=#0;

end;

procedure TForm1.N5Click(Sender: TObject);

begin

AboutForm.ShowModal;

end;

procedure TForm1.N1Click(Sender: TObject);

begin

NewAnketa;

end;

procedure TForm1.N3Click(Sender: TObject);

begin

Form1.Close;

end;

procedure TForm1.N2Click(Sender: TObject);

begin

Application.CreateForm(TInfoForm, InfoForm);

InfoForm.ShowModal;

end;

end.

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, jpeg, ExtCtrls;

type

TAboutForm = class(TForm)

Label1: TLabel;

Label2: TLabel;

Label3: TLabel;

Button1: TButton;

Image1: TImage;

private

{ Private declarations }

public

{ Public declarations }

end;

var

AboutForm: TAboutForm;

implementation

{$R *.dfm}

end.

unit Unit2;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, Grids, DB, ADODB, DBGrids;

type

TInfoForm = class(TForm)

InfoGrid: TStringGrid;

PriorButton: TButton;

NextButton: TButton;

DataSource1: TDataSource;

DBGrid1: TDBGrid;

ADO: TADOQuery;

Label1: TLabel;

CloseButton: TButton;

Label2: TLabel;

Button1: TButton;

Label3: TLabel;

edit1: TEdit;

procedure FormCreate(Sender: TObject);

procedure PriorButtonClick(Sender: TObject);

procedure NextButtonClick(Sender: TObject);

procedure CloseButtonClick(Sender: TObject);

procedure Button1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

InfoForm: TInfoForm;

implementation

uses Mainform;

{$R *.dfm}

procedure SelectInfo;

begin

with InfoForm do

begin

InfoGrid.Cells[1,0]:=ado.FieldByName('id').AsString;

InfoGrid.Cells[1,1]:=ado.FieldByName('name').AsString;

InfoGrid.Cells[1,2]:=ado.FieldByName('fam').AsString;

InfoGrid.Cells[1,3]:=ado.FieldByName('Otch').AsString;

if ado.FieldByName('pol').AsBoolean then InfoGrid.Cells[1,4]:='Женский' else InfoGrid.Cells[1,4]:='Мужской';

InfoGrid.Cells[1,5]:=ado.FieldByName('professia').AsString;

InfoGrid.Cells[1,6]:=ado.FieldByName('DataR').Asstring;

InfoGrid.Cells[1,7]:=Form1.TimeGameBox.Items[ado.FieldByName('TimeGame').AsInteger];

InfoGrid.Cells[1,8]:=Form1.OpitGameBox.Items[ado.FieldByName('OpitGame').AsInteger];

InfoGrid.Cells[1,9]:=ado.FieldByName('GanrGame').AsString;

InfoGrid.Cells[1,10]:=Form1.PlatformerBox.Items[ado.FieldByName('Platformer').Asinteger];

InfoGrid.Cells[1,11]:=ado.FieldByName('OS').AsString;

InfoGrid.Cells[1,12]:=ado.FieldByName('ConfigPC').AsString;

InfoGrid.Cells[1,13]:=Form1.PristavkaGroup.Items[ado.FieldByName('Pristavka').Asinteger];

InfoGrid.Cells[1,14]:=ado.FieldByName('Game').AsString;

InfoGrid.Cells[1,15]:=ado.FieldByName('GameInfo').AsString;

InfoGrid.Cells[1,16]:=Form1.DonatBox.Items[ado.FieldByName('Donat').AsInteger];

InfoGrid.Cells[1,17]:=ado.FieldByName('Film').AsString;

InfoGrid.Cells[1,18]:=ado.FieldByName('Info').AsString;

end;

end;

procedure TInfoForm.FormCreate(Sender: TObject);

begin

try

ADO.SQL.Clear;

ADO.sql.Text:='select * from Table_1 order by id asc;';

ADO.Open;

PriorButton.enabled:=true;

NextButton.enabled:=true;

ADO.last;

label2.Caption:='Всего анкет: '+ado.FieldByName('id').AsString+' ';

ado.First;

infogrid.ColWidths[0]:=220;

infogrid.ColWidths[1]:=680;

InfoGrid.Cells[0,0]:='Номер анкеты';

InfoGrid.Cells[0,1]:='Имя';

InfoGrid.Cells[0,2]:='Фамилия';

InfoGrid.Cells[0,3]:='Отчество';

InfoGrid.Cells[0,4]:='Пол';

InfoGrid.Cells[0,5]:='Профессия';

InfoGrid.Cells[0,6]:='Дата рождения';

InfoGrid.Cells[0,7]:='Время затрачиваемое на игры';

InfoGrid.Cells[0,8]:='Игровой опыт';

InfoGrid.Cells[0,9]:='Любимый жанр игр';

InfoGrid.Cells[0,10]:='Отношение к платформерам';

InfoGrid.Cells[0,11]:='Операционная система';

InfoGrid.Cells[0,12]:='Конфигурация компьютера';

InfoGrid.Cells[0,13]:='Наличие приставки';

InfoGrid.Cells[0,14]:='Любимая игра';

InfoGrid.Cells[0,15]:='Информация о любимой игре';

InfoGrid.Cells[0,16]:='Трача денег на игры';

InfoGrid.Cells[0,17]:='Любимый фильм';

InfoGrid.Cells[0,18]:='Информация о себе';

selectInfo;

except

ShowMessage('Не найдено данных!');

PriorButton.Enabled:=false;

NextButton.Enabled:=false;

end;

end;

procedure TInfoForm.PriorButtonClick(Sender: TObject);

begin

Ado.prior;

selectInfo;

end;

procedure TInfoForm.NextButtonClick(Sender: TObject);

begin

Ado.next;

selectInfo;

end;

procedure TInfoForm.Button1Click(Sender: TObject);

var

i:integer; //счетчик

begin

i:=1;

ado.Last;

if (strtoint(edit1.text)<=ado.FieldByName('id').AsInteger)and(strtoint(edit1.text)>0) then

begin

ado.First;

while i<strtoint(edit1.text) do

begin

ado.Next;

i:=i+1;

end;

selectInfo; end else

begin

ShowMessage('Введите правильное значение номера анкеты!');

edit1.clear;

end;

end;

procedure TInfoForm.CloseButtonClick(Sender: TObject);

begin

InfoForm.Release;

end;

end.

29

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]