Інформаційна система торгівельного закладу

Створення інформаційної системи для спортивного магазину харчування. Обґрунтування вибору мови програмування. Текстуальний опис алгоритму. Проектування бази даних. Комп'ютеризація торгівельних закладів, отримання необхідних даних в автоматичному режимі.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык украинский
Дата добавления 12.05.2015
Размер файла 1,3 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

this.tabControl.Location = new System.Drawing.Point(0, 0);

this.tabControl.Name = "tabControl";

this.tabControl.SelectedIndex = 0;

this.tabControl.Size = new System.Drawing.Size(651, 333);

this.tabControl.TabIndex = 1;

//

// tabPageCountries

//

this.tabPageCountries.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageCountries.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageCountries.Location = new System.Drawing.Point(4, 26);

this.tabPageCountries.Name = "tabPageCountries";

this.tabPageCountries.Padding = new System.Windows.Forms.Padding(3);

this.tabPageCountries.Size = new System.Drawing.Size(643, 303);

this.tabPageCountries.TabIndex = 0;

this.tabPageCountries.Text = "Страны";

//

// tabPageCities

//

this.tabPageCities.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageCities.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageCities.Location = new System.Drawing.Point(4, 26);

this.tabPageCities.Name = "tabPageCities";

this.tabPageCities.Padding = new System.Windows.Forms.Padding(3);

this.tabPageCities.Size = new System.Drawing.Size(643, 303);

this.tabPageCities.TabIndex = 1;

this.tabPageCities.Text = "Города";

//

// tabPageHotels

//

this.tabPageHotels.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageHotels.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageHotels.Location = new System.Drawing.Point(4, 26);

this.tabPageHotels.Name = "tabPageHotels";

this.tabPageHotels.Size = new System.Drawing.Size(643, 303);

this.tabPageHotels.TabIndex = 2;

this.tabPageHotels.Text = "Отели";

//

// tabPageServices

//

this.tabPageServices.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageServices.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageServices.Location = new System.Drawing.Point(4, 26);

this.tabPageServices.Name = "tabPageServices";

this.tabPageServices.Size = new System.Drawing.Size(643, 303);

this.tabPageServices.TabIndex = 3;

this.tabPageServices.Text = "Услуги";

//

// tabPageTours

//

this.tabPageTours.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageTours.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageTours.Location = new System.Drawing.Point(4, 26);

this.tabPageTours.Name = "tabPageTours";

this.tabPageTours.Size = new System.Drawing.Size(643, 303);

this.tabPageTours.TabIndex = 4;

this.tabPageTours.Text = "Туры";

//

// tabPageClients

//

this.tabPageClients.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageClients.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageClients.Location = new System.Drawing.Point(4, 26);

this.tabPageClients.Name = "tabPageClients";

this.tabPageClients.Size = new System.Drawing.Size(643, 303);

this.tabPageClients.TabIndex = 5;

this.tabPageClients.Text = "Клиенты";

//

// tabPageToursClients

//

this.tabPageToursClients.BackColor = System.Drawing.Color.WhiteSmoke;

this.tabPageToursClients.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.tabPageToursClients.Location = new System.Drawing.Point(4, 26);

this.tabPageToursClients.Name = "tabPageToursClients";

this.tabPageToursClients.Size = new System.Drawing.Size(643, 303);

this.tabPageToursClients.TabIndex = 6;

this.tabPageToursClients.Text = "Посетители туров";

//

// DatabaseForm

//

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

this.ClientSize = new System.Drawing.Size(651, 333);

this.Controls.Add(this.tabControl);

this.Name = "DatabaseForm";

this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

this.Text = "База данных";

this.Deactivate += new System.EventHandler(this.DatabaseForm_Deactivate);

this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.DatabaseForm_FormClosed);

this.Load += new System.EventHandler(this.DatabaseForm_Load);

this.Enter += new System.EventHandler(this.DatabaseForm_Enter);

this.tabControl.ResumeLayout(false);

this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.TabControl tabControl;

private System.Windows.Forms.TabPage tabPageCountries;

private System.Windows.Forms.TabPage tabPageCities;

private System.Windows.Forms.TabPage tabPageHotels;

private System.Windows.Forms.TabPage tabPageServices;

private System.Windows.Forms.TabPage tabPageTours;

private System.Windows.Forms.TabPage tabPageClients;

private System.Windows.Forms.TabPage tabPageToursClients;

}

Файл FormExtensions.cs

using System;

using System.Drawing;

using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace TurFirm

{

// Клас расширений для формы.

public static class FormExtensions

{

[DllImport("user32.dll")]

private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

[DllImport("user32.dll")]

private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

[DllImport("user32.dll", ExactSpelling = true)]

private static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

private const int GWL_EXSTYLE = -20;

private const int WS_EX_CLIENTEDGE = 0x200;

private const uint SWP_NOSIZE = 0x0001;

private const uint SWP_NOMOVE = 0x0002;

private const uint SWP_NOZORDER = 0x0004;

private const uint SWP_NOREDRAW = 0x0008;

private const uint SWP_NOACTIVATE = 0x0010;

private const uint SWP_FRAMECHANGED = 0x0020;

private const uint SWP_SHOWWINDOW = 0x0040;

private const uint SWP_HIDEWINDOW = 0x0080;

private const uint SWP_NOCOPYBITS = 0x0100;

private const uint SWP_NOOWNERZORDER = 0x0200;

private const uint SWP_NOSENDCHANGING = 0x0400;

// Убирает рамку у MdiClient, если второй параметр задан как false.

public static bool SetBevel(this Form form, bool show)

{

var client = form.GetMdiClient();

if (client == null)

return false;

int windowLong = GetWindowLong(client.Handle, GWL_EXSTYLE);

if (show)

windowLong |= WS_EX_CLIENTEDGE;

else

windowLong &= ~WS_EX_CLIENTEDGE;

SetWindowLong(client.Handle, GWL_EXSTYLE, windowLong);

SetWindowPos(client.Handle, IntPtr.Zero, 0, 0, 0, 0,

SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |

SWP_NOOWNERZORDER | SWP_FRAMECHANGED);

return true;

}

// Устанавливает цвет фона Mdi-формы.

public static void SetMdiFormBackColor(this Form form, Color color)

{

var client = form.GetMdiClient();

if (client == null)

return;

client.BackColor = color;

}

// Возвращает MdiClient формы.

public static MdiClient GetMdiClient(this Form form)

{

foreach (Control c in form.Controls)

{

var client = c as MdiClient;

if (client == null)

continue;

return client;

}

return null;

}

}

Файл TurSearchForm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace TurFirm

{

public partial class ProjectSearchForm: Form

{

DataTable dataTable; // таблиця, в якій відбувається пошук

public delegate void SearchButtonClick(int rowIndex); // rowIndex - індекс шуканого рядка

public event SearchButtonClick SearchResult; // подія, яка трапляється при натисканні кнопки пошуку

public ProjectSearchForm(DataTable _dataTable)

InitializeComponent();

this.dataTable = _dataTable;

}

private void btnSearch_Click(object sender, EventArgs e)

{

DataRow[] dataRows; // масив знайдених рядків

DataRow searchRow; // шуканий рядок

string searchKey = ""; // ключ пошуку

bool isOk = true; // флаг, який вказує, чи виникло виключення під час пошуку

dataRows = new DataRow[0]; /* цей запис необхідний, щоб середа розробки не видавала помилку

* про використання неініціалізованої змінної */

if (cbNumber.Checked)

searchKey += "№ = " + tbNumber.Text;

if (cbName_Pr.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "Name_Pr = '" + tbName_Pr.Text + "'";

}

if (cbZakazchik.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "Zakazchik = '" + tbZakazchik.Text + "'";

}

if (cbShifr.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "Shifr = '" + tbShifr.Text + "'";

}

if (cbCost_Pr.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "Cost_Pr = " + tbCost_Pr.Text;

}

if (cbN_Otdel.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "№_Otdel = " + tbN_Otdel.Text;

}

if (cbN_Dogovor.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "№_Dogovor = " + tbN_Dogovor.Text;

}

if (cbStatyc.Checked)

{

if (searchKey != "")

searchKey += " AND ";

searchKey += "Statyc = '" + tbStatyc.Text + "'";

}

if (searchKey == "")

{

MessageBox.Show("Задайте умову пошуку і повторіть запит.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

return;

}

try

{

dataRows = dataTable.Select(searchKey);

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

if (!isOk)

return;

if (dataRows.Length == 0) // якщо пошук нічого не знайшов

{

MessageBox.Show("Вибачте, але нічого не знайдено.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

return;

}

searchRow = dataRows[0]; // беремо перший рядок серед знайдених

for (int i = 0; i < dataTable.Rows.Count; i++)

if (searchRow == dataTable.Rows[i])

{

SearchResult(i);

return;

}

SearchResult(-1);

}

Файл InternetForm.cs

using System;

using System.Drawing;

using System.Windows.Forms;

namespace TurFirm

{

// Форма для выхода в Интернет.

public partial class InternetForm: Form

{

// Экземпляр формы.

public static InternetForm Instance { get; private set; }

// Кнопка, которая отвечает за экземпляр формы.

public static Button InstanceButton { get; private set; }

public InternetForm(Button instanceButton)

{

InitializeComponent();

Instance = this;

InstanceButton = instanceButton;

}

private void InternetForm_Load(object sender, EventArgs e)

{

ControlBox = false;

WindowState = FormWindowState.Maximized;

tsbHome.PerformClick();

}

private void InternetForm_Enter(object sender, EventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.LightBlue);

}

private void InternetForm_Deactivate(object sender, EventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.Empty);

}

private void InternetForm_FormClosed(object sender, FormClosedEventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.Empty);

InstanceButton = null;

Instance = null;

}

private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

{

tstxtLink.Text = webBrowser.Url.AbsoluteUri;

}

// Переходит по указанному веб-адресу.

private void tsbGo_Click(object sender, EventArgs e)

{

webBrowser.Navigate(tstxtLink.Text);

}

// Обновляет веб-страницу.

private void tsbRefresh_Click(object sender, EventArgs e)

{

webBrowser.Refresh();

}

// Переходит на предыдущую веб-страницу.

private void tsbBackward_Click(object sender, EventArgs e)

{

webBrowser.GoBack();

}

// Переходит на следующую веб-страницу.

private void tsbForward_Click(object sender, EventArgs e)

{

webBrowser.GoForward();

}

// Переходит на домашнюю веб-страницу.

private void tsbHome_Click(object sender, EventArgs e)

{

webBrowser.GoHome();

}

// Вызывает переход по указанному веб-адресу, когда нажимается Enter, если фокус ввода в поле веб-адреса.

private void tstxtLink_KeyDown(object sender, KeyEventArgs e)

{

if (e.KeyData == Keys.Enter)

{

tsbGo.PerformClick();

e.SuppressKeyPress = true; // нужно для того, чтобы не срабатывал раздражающий системный звук

}

Файл InternetForm.Designer.cs

namespace TurFirm

{

partial class InternetForm

{

/// <summary>

/// Required designer variable.

/// </summary>

private System.ComponentModel.IContainer components = null;

/// <summary>

/// Clean up any resources being used.

/// </summary>

/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

/// </summary>

private void InitializeComponent()

{

this.toolStrip = new System.Windows.Forms.ToolStrip();

this.tsbBackward = new System.Windows.Forms.ToolStripButton();

this.tsbForward = new System.Windows.Forms.ToolStripButton();

this.tsbRefresh = new System.Windows.Forms.ToolStripButton();

this.tsbHome = new System.Windows.Forms.ToolStripButton();

this.tstxtLink = new System.Windows.Forms.ToolStripTextBox();

this.tsbGo = new System.Windows.Forms.ToolStripButton();

this.webBrowser = new System.Windows.Forms.WebBrowser();

this.toolStrip.SuspendLayout();

this.SuspendLayout();

//

// toolStrip

//

this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;

this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {

this.tsbBackward,

this.tsbForward,

this.tsbRefresh,

this.tsbHome,

this.tstxtLink,

this.tsbGo});

this.toolStrip.Location = new System.Drawing.Point(0, 0);

this.toolStrip.Name = "toolStrip";

this.toolStrip.Padding = new System.Windows.Forms.Padding(3, 0, 1, 0);

this.toolStrip.Size = new System.Drawing.Size(692, 31);

this.toolStrip.TabIndex = 0;

this.toolStrip.Text = "toolStrip1";

//

// tsbBackward

//

this.tsbBackward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

this.tsbBackward.Image = global::TurFirm.Properties.Resources.Backward_24;

this.tsbBackward.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;

this.tsbBackward.ImageTransparentColor = System.Drawing.Color.Magenta;

this.tsbBackward.Margin = new System.Windows.Forms.Padding(2, 1, 2, 2);

this.tsbBackward.Name = "tsbBackward";

this.tsbBackward.Size = new System.Drawing.Size(28, 28);

this.tsbBackward.Text = "Назад";

this.tsbBackward.Click += new System.EventHandler(this.tsbBackward_Click);

//

// tsbForward

//

this.tsbForward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

this.tsbForward.Image = global::TurFirm.Properties.Resources.Forward_24;

this.tsbForward.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;

this.tsbForward.ImageTransparentColor = System.Drawing.Color.Magenta;

this.tsbForward.Margin = new System.Windows.Forms.Padding(2, 1, 2, 2);

this.tsbForward.Name = "tsbForward";

this.tsbForward.Size = new System.Drawing.Size(28, 28);

this.tsbForward.Text = "Вперед";

this.tsbForward.Click += new System.EventHandler(this.tsbForward_Click);

//

// tsbRefresh

//

this.tsbRefresh.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

this.tsbRefresh.Image = global::TurFirm.Properties.Resources.Refresh_24;

this.tsbRefresh.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;

this.tsbRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;

this.tsbRefresh.Margin = new System.Windows.Forms.Padding(2, 1, 2, 2);

this.tsbRefresh.Name = "tsbRefresh";

this.tsbRefresh.Size = new System.Drawing.Size(28, 28);

this.tsbRefresh.Text = "Обновить";

this.tsbRefresh.Click += new System.EventHandler(this.tsbRefresh_Click);

//

// tsbHome

//

this.tsbHome.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

this.tsbHome.Image = global::TurFirm.Properties.Resources.Home_20;

this.tsbHome.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;

this.tsbHome.ImageTransparentColor = System.Drawing.Color.Magenta;

this.tsbHome.Margin = new System.Windows.Forms.Padding(2, 1, 2, 2);

this.tsbHome.Name = "tsbHome";

this.tsbHome.Size = new System.Drawing.Size(28, 28);

this.tsbHome.Text = "Домой";

this.tsbHome.Click += new System.EventHandler(this.tsbHome_Click);

//

// tstxtLink

//

this.tstxtLink.Name = "tstxtLink";

this.tstxtLink.Size = new System.Drawing.Size(500, 31);

this.tstxtLink.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tstxtLink_KeyDown);

//

// tsbGo

//

this.tsbGo.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;

this.tsbGo.Image = global::TurFirm.Properties.Resources.Go_24;

this.tsbGo.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;

this.tsbGo.ImageTransparentColor = System.Drawing.Color.Magenta;

this.tsbGo.Name = "tsbGo";

this.tsbGo.Size = new System.Drawing.Size(28, 28);

this.tsbGo.Text = "Перейти на страницу";

this.tsbGo.Click += new System.EventHandler(this.tsbGo_Click);

//

// webBrowser

//

this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;

this.webBrowser.Location = new System.Drawing.Point(0, 31);

this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20);

this.webBrowser.Name = "webBrowser";

this.webBrowser.Size = new System.Drawing.Size(692, 392);

this.webBrowser.TabIndex = 1;

this.webBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser_DocumentCompleted);

//

// InternetForm

//

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

this.ClientSize = new System.Drawing.Size(692, 423);

this.Controls.Add(this.webBrowser);

this.Controls.Add(this.toolStrip);

this.Name = "InternetForm";

this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

this.Text = "Интернет";

this.Deactivate += new System.EventHandler(this.InternetForm_Deactivate);

this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.InternetForm_FormClosed);

this.Load += new System.EventHandler(this.InternetForm_Load);

this.Enter += new System.EventHandler(this.InternetForm_Enter);

this.toolStrip.ResumeLayout(false);

this.toolStrip.PerformLayout();

this.ResumeLayout(false);

this.PerformLayout();

}

#endregion

private System.Windows.Forms.ToolStrip toolStrip;

private System.Windows.Forms.ToolStripButton tsbBackward;

private System.Windows.Forms.ToolStripButton tsbForward;

private System.Windows.Forms.ToolStripButton tsbRefresh;

private System.Windows.Forms.ToolStripButton tsbHome;

private System.Windows.Forms.ToolStripTextBox tstxtLink;

private System.Windows.Forms.ToolStripButton tsbGo;

private System.Windows.Forms.WebBrowser webBrowser;

}

Файл MainForm.cs

using System;

using System.Drawing;

using System.Windows.Forms;

using TurFirm.Properties;

using Slusser.Components;

namespace TurFirm

{

// Главная форма программы.

public partial class MainForm: Form

{

private bool _menuVisible; // видимость панели меню

private readonly MdiClientController _mdiClientController;

public MainForm()

{

InitializeComponent();

_menuVisible = true;

_mdiClientController = new MdiClientController(this)

{

BorderStyle = BorderStyle.None,

BackColor = ControlPaint.LightLight(Color.LightGray),

Image = Resources.Logo,

ImageAlign = ContentAlignment.TopCenter

};

_mdiClientController.Paint += MdiClient_Paint;

}

// Прячет или скрывает панель меню.

private bool MenuVisible

{

get { return _menuVisible; }

set

{

_menuVisible = value;

pnlMenu.Visible = value;

btnMenuVisible.Image = value ? Resources.Left_36: Resources.Right_36;

toolTip.SetToolTip(btnMenuVisible, value ? "Скрыть панель меню": "Открыть панель меню");

Refresh();

}

// Скрывает или делает видимой панель меню.

private void btnMenuVisible_Click(object sender, EventArgs e)

{

MenuVisible = !MenuVisible;

}

// Открывает форму для редактирования таблиц базы данных.

private void btnDatabase_Click(object sender, EventArgs e)

{

if (DatabaseForm.Instance == null)

new DatabaseForm(btnDatabase) {MdiParent = this}.Show();

else

DatabaseForm.Instance.Focus();

}

// Открывает форму для входа в Интернет.

private void btnInternet_Click(object sender, EventArgs e)

{

if (InternetForm.Instance == null)

new InternetForm(btnInternet) {MdiParent = this}.Show();

else

InternetForm.Instance.Focus();

}

// Открывает форму для написания и выполнения запросов к базе данных.

private void btnSqlEditor_Click(object sender, EventArgs e)

{

if (QueryForm.Instance == null)

new QueryForm(btnSqlEditor) {MdiParent = this}.Show();

else

QueryForm.Instance.Focus();

}

// Рисует изображения на фоне MdiClient.

private void MdiClient_Paint(object sender, PaintEventArgs e)

{

// Рисуем подсказку.

if (MenuVisible)

{

var introImageRectangle =

new Rectangle(new Point(10, DisplayRectangle.Height - Resources.IntroduceText.Height - 30),

Resources.IntroduceText.Size);

e.Graphics.DrawImageUnscaledAndClipped(Resources.IntroduceText, introImageRectangle);

}

Файл AddTurForm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.OleDb;

namespace TurFirm

{

public partial class AddProjectForm: Form, IUpdateForm

{

private OleDbConnection connection;

private OleDbCommand command;

private MainForm mainForm; // посилання на об'єкт головної форми

private DataSet dataSet;

private OleDbDataAdapter dataAdapter;

public AddProjectForm(OleDbConnection _connection, MainForm _mainForm)

{

InitializeComponent();

this.connection = _connection;

this.mainForm = _mainForm;

}

private void AddProjectForm_Load(object sender, EventArgs e)

{

bool isOk = true; // флаг, чи успішно виконалися запити

mainForm.OpenedFormCollection.Add(this);

dataSet = new DataSet();

command = new OleDbCommand();

command.Connection = connection;

dataAdapter = new OleDbDataAdapter();

dataAdapter.SelectCommand = command;

try

{

connection.Open();

command.CommandText = "SELECT * FROM Vedomstva";

dataAdapter.Fill(dataSet, "Vedomstva");

command.CommandText = "SELECT * FROM Dogovori";

dataAdapter.Fill(dataSet, "Dogovori");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (!isOk)

this.Close();

cbN_Otdel.DataSource = dataSet.Tables["Vedomstva"];

cbN_Otdel.DisplayMember = "Name_Otdel";

cbN_Otdel.ValueMember = "№_Otdel";

cbN_Otdel.SelectedIndex = 0;

cbN_Dogovor.DataSource = dataSet.Tables["Dogovori"];

cbN_Dogovor.DisplayMember = "Nazvanie_dog";

cbN_Dogovor.ValueMember = "№";

cbN_Dogovor.SelectedIndex = 0;

}

private void AddProjectForm_FormClosed(object sender, FormClosedEventArgs e)

{

mainForm.OpenedFormCollection.Remove(this);

}

private void btnClose_Click(object sender, EventArgs e)

{

this.Close();

}

private void btnOK_Click(object sender, EventArgs e)

{

bool isOk = true; // флаг, чи успішно виконався запит

string commandText;

command Text = "INSERT INTO Project(№,Name_Pr,Zakazchik,Shifr,Cost_Pr,№_Otdel,№_Dogovor,Statyc) VALUES("

+ tbNumber.Text + ","

+ "'" + tbName_Pr.Text + "',"

+ "'" + tbZakazchik.Text + "',"

+ "'" + tbShifr.Text + "',"

+ tbCost_Pr.Text + ","

+ cbN_Otdel.SelectedValue.ToString() + ","

+ cbN_Dogovor.SelectedValue.ToString() + ","

+ "'" + cbStatyc.Text + "')";

command.CommandText = commandText;

try

{

connection.Open();

command.ExecuteNonQuery();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (isOk)

{

// Очищаємо елементи на формі

tbNumber.Clear();

tbName_Pr.Clear();

tbZakazchik.Clear();

tbShifr.Clear();

tbCost_Pr.Clear();

cbN_Otdel.SelectedIndex = 0;

cbN_Dogovor.SelectedIndex = 0;

cbStatyc.Text = "";

}

// Оновлюємо дані у формах

mainForm.OpenedFormCollection.UpdateAll();

}

public void UpdateForm()

{

bool isOk = true; // флаг, чи успішно виконалися запити

int indexN_Otdel = cbN_Otdel.SelectedIndex; // зберігаємо поточні індекси елементів ComboBox

int indexN_Dogovor = cbN_Dogovor.SelectedIndex;

dataSet.Tables["Vedomstva"].Clear();

dataSet.Tables["Dogovori"].Clear();

try

{

connection.Open();

command.CommandText = "SELECT * FROM Vedomstva";

dataAdapter.Fill(dataSet, "Vedomstva");

command.CommandText = "SELECT * FROM Dogovori";

dataAdapter.Fill(dataSet, "Dogovori");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (!isOk)

this.Close();

if (indexN_Otdel < cbN_Otdel.Items.Count)

cbN_Otdel.SelectedIndex = indexN_Otdel;

if (indexN_Dogovor < cbN_Dogovor.Items.Count)

cbN_Dogovor.SelectedIndex = indexN_Dogovor;

}

Файл MainForm.Designer.cs

namespace TurFirm

{

partial class MainForm

{

/// <summary>

/// Требуется переменная конструктора.

/// </summary>

private System.ComponentModel.IContainer components = null;

/// <summary>

/// Освободить все используемые ресурсы.

/// </summary>

/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Код, автоматически созданный конструктором форм Windows

/// <summary>

/// Обязательный метод для поддержки конструктора - не изменяйте

/// содержимое данного метода при помощи редактора кода.

/// </summary>

private void InitializeComponent()

{

this.components = new System.ComponentModel.Container();

System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));

this.pnlMenu = new System.Windows.Forms.Panel();

this.btnAbout = new System.Windows.Forms.Button();

this.btnHelp = new System.Windows.Forms.Button();

this.btnSqlEditor = new System.Windows.Forms.Button();

this.btnInternet = new System.Windows.Forms.Button();

this.btnDatabase = new System.Windows.Forms.Button();

this.btnAddTour = new System.Windows.Forms.Button();

this.toolTip = new System.Windows.Forms.ToolTip(this.components);

this.btnMenuVisible = new System.Windows.Forms.Button();

this.pnlBorder = new System.Windows.Forms.Panel();

this.pnlMenu.SuspendLayout();

this.SuspendLayout();

//

// pnlMenu

//

this.pnlMenu.AutoScroll = true;

this.pnlMenu.BackColor = System.Drawing.Color.WhiteSmoke;

this.pnlMenu.Controls.Add(this.btnAbout);

this.pnlMenu.Controls.Add(this.btnHelp);

this.pnlMenu.Controls.Add(this.btnSqlEditor);

this.pnlMenu.Controls.Add(this.btnInternet);

this.pnlMenu.Controls.Add(this.btnDatabase);

this.pnlMenu.Controls.Add(this.btnAddTour);

this.pnlMenu.Dock = System.Windows.Forms.DockStyle.Left;

this.pnlMenu.Location = new System.Drawing.Point(57, 0);

this.pnlMenu.Name = "pnlMenu";

this.pnlMenu.Size = new System.Drawing.Size(131, 390);

this.pnlMenu.TabIndex = 0;

//

// btnAbout

//

this.btnAbout.Dock = System.Windows.Forms.DockStyle.Top;

this.btnAbout.FlatAppearance.BorderSize = 0;

this.btnAbout.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnAbout.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnAbout.ForeColor = System.Drawing.Color.IndianRed;

this.btnAbout.Image = global::TurFirm.Properties.Resources.Information_70;

this.btnAbout.Location = new System.Drawing.Point(0, 535);

this.btnAbout.Name = "btnAbout";

this.btnAbout.Size = new System.Drawing.Size(114, 107);

this.btnAbout.TabIndex = 5;

this.btnAbout.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnAbout, "О программе");

this.btnAbout.UseVisualStyleBackColor = true;

//

// btnHelp

//

this.btnHelp.Dock = System.Windows.Forms.DockStyle.Top;

this.btnHelp.FlatAppearance.BorderSize = 0;

this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnHelp.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnHelp.ForeColor = System.Drawing.Color.IndianRed;

this.btnHelp.Image = global::TurFirm.Properties.Resources.Help_70;

this.btnHelp.Location = new System.Drawing.Point(0, 428);

this.btnHelp.Name = "btnHelp";

this.btnHelp.Size = new System.Drawing.Size(114, 107);

this.btnHelp.TabIndex = 4;

this.btnHelp.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnHelp, "Справка");

this.btnHelp.UseVisualStyleBackColor = true;

//

// btnSqlEditor

//

this.btnSqlEditor.Dock = System.Windows.Forms.DockStyle.Top;

this.btnSqlEditor.FlatAppearance.BorderSize = 0;

this.btnSqlEditor.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnSqlEditor.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnSqlEditor.ForeColor = System.Drawing.Color.IndianRed;

this.btnSqlEditor.Image = global::TurFirm.Properties.Resources.Sql_70;

this.btnSqlEditor.Location = new System.Drawing.Point(0, 321);

this.btnSqlEditor.Name = "btnSqlEditor";

this.btnSqlEditor.Size = new System.Drawing.Size(114, 107);

this.btnSqlEditor.TabIndex = 3;

this.btnSqlEditor.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnSqlEditor, "Редактор запросов");

this.btnSqlEditor.UseVisualStyleBackColor = true;

this.btnSqlEditor.Click += new System.EventHandler(this.btnSqlEditor_Click);

//

// btnInternet

//

this.btnInternet.Dock = System.Windows.Forms.DockStyle.Top;

this.btnInternet.FlatAppearance.BorderSize = 0;

this.btnInternet.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnInternet.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnInternet.ForeColor = System.Drawing.Color.IndianRed;

this.btnInternet.Image = global::TurFirm.Properties.Resources.Earth_70;

this.btnInternet.Location = new System.Drawing.Point(0, 214);

this.btnInternet.Name = "btnInternet";

this.btnInternet.Size = new System.Drawing.Size(114, 107);

this.btnInternet.TabIndex = 2;

this.btnInternet.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnInternet, "Интернет");

this.btnInternet.UseVisualStyleBackColor = true;

this.btnInternet.Click += new System.EventHandler(this.btnInternet_Click);

//

// btnDatabase

//

this.btnDatabase.Dock = System.Windows.Forms.DockStyle.Top;

this.btnDatabase.FlatAppearance.BorderSize = 0;

this.btnDatabase.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnDatabase.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnDatabase.ForeColor = System.Drawing.Color.IndianRed;

this.btnDatabase.Image = global::TurFirm.Properties.Resources.Database_73_70;

this.btnDatabase.Location = new System.Drawing.Point(0, 107);

this.btnDatabase.Name = "btnDatabase";

this.btnDatabase.Size = new System.Drawing.Size(114, 107);

this.btnDatabase.TabIndex = 1;

this.btnDatabase.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnDatabase, "База данных");

this.btnDatabase.UseVisualStyleBackColor = true;

this.btnDatabase.Click += new System.EventHandler(this.btnDatabase_Click);

//

// btnAddTour

//

this.btnAddTour.Dock = System.Windows.Forms.DockStyle.Top;

this.btnAddTour.FlatAppearance.BorderSize = 0;

this.btnAddTour.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnAddTour.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.btnAddTour.ForeColor = System.Drawing.Color.IndianRed;

this.btnAddTour.Image = global::TurFirm.Properties.Resources.Beach_78_70;

this.btnAddTour.Location = new System.Drawing.Point(0, 0);

this.btnAddTour.Name = "btnAddTour";

this.btnAddTour.Size = new System.Drawing.Size(114, 107);

this.btnAddTour.TabIndex = 0;

this.btnAddTour.TextAlign = System.Drawing.ContentAlignment.BottomCenter;

this.toolTip.SetToolTip(this.btnAddTour, "Оформить тур");

this.btnAddTour.UseVisualStyleBackColor = true;

//

// btnMenuVisible

//

this.btnMenuVisible.BackColor = System.Drawing.Color.WhiteSmoke;

this.btnMenuVisible.Dock = System.Windows.Forms.DockStyle.Left;

this.btnMenuVisible.FlatAppearance.BorderSize = 0;

this.btnMenuVisible.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

this.btnMenuVisible.Image = global::TurFirm.Properties.Resources.Left_36;

this.btnMenuVisible.ImageAlign = System.Drawing.ContentAlignment.TopCenter;

this.btnMenuVisible.Location = new System.Drawing.Point(0, 0);

this.btnMenuVisible.Name = "btnMenuVisible";

this.btnMenuVisible.Padding = new System.Windows.Forms.Padding(0, 5, 0, 0);

this.btnMenuVisible.Size = new System.Drawing.Size(57, 390);

this.btnMenuVisible.TabIndex = 2;

this.toolTip.SetToolTip(this.btnMenuVisible, "Скрыть панель меню");

this.btnMenuVisible.UseVisualStyleBackColor = false;

this.btnMenuVisible.Click += new System.EventHandler(this.btnMenuVisible_Click);

//

// pnlBorder

//

this.pnlBorder.BackColor = System.Drawing.Color.LightGray;

this.pnlBorder.Dock = System.Windows.Forms.DockStyle.Left;

this.pnlBorder.Location = new System.Drawing.Point(188, 0);

this.pnlBorder.Name = "pnlBorder";

this.pnlBorder.Size = new System.Drawing.Size(1, 390);

this.pnlBorder.TabIndex = 4;

//

// MainForm

//

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

this.ClientSize = new System.Drawing.Size(1058, 701);

this.Controls.Add(this.pnlBorder);

this.Controls.Add(this.pnlMenu);

this.Controls.Add(this.btnMenuVisible);

this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

this.IsMdiContainer = true;

this.MinimumSize = new System.Drawing.Size(860, 428);

this.Name = "MainForm";

this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

this.Text = "Сказочный тур";

this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

this.Paint += new System.Windows.Forms.PaintEventHandler(this.MdiClient_Paint);

this.pnlMenu.ResumeLayout(false);

this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.Panel pnlMenu;

private System.Windows.Forms.Button btnMenuVisible;

private System.Windows.Forms.Button btnAddTour;

private System.Windows.Forms.Button btnDatabase;

private System.Windows.Forms.ToolTip toolTip;

private System.Windows.Forms.Button btnInternet;

private System.Windows.Forms.Button btnSqlEditor;

private System.Windows.Forms.Button btnHelp;

private System.Windows.Forms.Button btnAbout;

private System.Windows.Forms.Panel pnlBorder;

}

Файл AddVedomstvaForm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.OleDb;

namespace TurFirm

{

public partial class AddVedomstvaForm: Form

{

private OleDbConnection connection;

private OleDbCommand command;

private MainForm mainForm; // посилання на об'єкт головної форми

public AddVedomstvaForm(OleDbConnection _connection, MainForm _mainForm)

{

InitializeComponent();

this.connection = _connection;

this.mainForm = _mainForm;

}

private void AddVedomstvaForm_Load(object sender, EventArgs e)

{

mainForm.OpenedFormCollection.Add(this);

command = new OleDbCommand();

command.Connection = connection;

}

private void AddVedomstvaForm_FormClosed(object sender, FormClosedEventArgs e)

{

mainForm.OpenedFormCollection.Remove(this);

}

private void btnClose_Click(object sender, EventArgs e)

{

this.Close();

}

private void btnOK_Click(object sender, EventArgs e)

{

bool isOk = true;

string commandText;

commandText = "INSERT INTO Vedomstva(Name_Otdel,Phone) VALUES("

+ "'" + tbName_Otdel.Text + "',"

+ "'" + tbPhone.Text + "')";

command.CommandText = commandText;

try

{

connection.Open();

command.ExecuteNonQuery();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (isOk)

{

// Очищаємо елементи на формі

tbName_Otdel.Clear();

tbPhone.Clear();

}

// Оновлюємо дані у формах

mainForm.OpenedFormCollection.UpdateAll();

}

Файл OleDbPackage.cs

using System.Data;

using System.Data.OleDb;

namespace TurFirm

{

// Необходимые программе инструменты для работы с ADO.NET.

public static class OleDbPackage

{

private static readonly OleDbCommand Command; // команда для запросов, не возвращающих данных

private static readonly OleDbDataAdapter Adapter; // адаптер базы данных

private static readonly OleDbConnection Connection; // соединение к базе данных

private const string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=turfirm.mdb"; // строка подключения к базе данных

static OleDbPackage()

{

Connection = new OleDbConnection(ConnectionString);

Command = Connection.CreateCommand();

Adapter = new OleDbDataAdapter {SelectCommand = Connection.CreateCommand()};

}

// Выполняет команду, которая не возвращает данных.

public static void ExecuteCommand(string commandText)

{

Command.CommandText = commandText;

try

{

OpenConnection();

Command.ExecuteNonQuery();

}

finally

{

CloseConnection();

}

// Выполняет команду, возвращающую единственное значение.

public static object ExecuteScalar(string commandText)

{

Command.CommandText = commandText;

try

{

OpenConnection();

return Command.ExecuteScalar();

}

finally

{

CloseConnection();

}

}

// Возвращает таблицу, построенную на основе переданного запроса.

public static DataTable ExecuteTable(string commandText)

{

var dataTable = new DataTable();

FillTable(dataTable, commandText);

return dataTable;

}

// Заполняет указанную таблицу, использую переданный текст запроса.

public static void FillTable(DataTable dataTable, string commandText)

{

Adapter.SelectCommand.CommandText = commandText;

try

{

OpenConnection();

Adapter.Fill(dataTable);

}

finally

{

CloseConnection();

}

// Обновляет базу данных, используя переданную таблицу изменений.

public static void UpdateTable(DataTable changesTable, string selectCommandText)

{

Adapter.SelectCommand.CommandText = selectCommandText;

try

{

OpenConnection();

var commandBuilder = new OleDbCommandBuilder(Adapter);

Adapter.Update(changesTable);

}

finally

{

CloseConnection();

}

// Тестирует, возможно ли соединение с базой данных.

public static bool TryConnection()

{

try

{

OpenConnection();

ExecuteCommand("SELECT 1");

CloseConnection();

return true;

}

catch

{

return false;

}

// Открывает соединение с базой данных.

private static void OpenConnection()

{

if (Connection.State != ConnectionState.Open)

Connection.Open();

}

// Закрывает соединение с базой данных.

private static void CloseConnection()

{

Connection.Close();

}

Файл Program.cs

using System;

using System.Windows.Forms;

namespace TurFirm

{

static class Program

{

/// <summary>

/// Главная точка входа для приложения.

/// </summary>

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

if (!OleDbPackage.TryConnection())

{

MessageBox.Show(

"Соединение с базой данных не установлено. Вероятно, файл с базой данных turfirm.mdb отсутствует в каталоге с программой.",

"Сказочный тур", MessageBoxButtons.OK, MessageBoxIcon.Error);

return;

}

Application.Run(new MainForm());

}

Файл QueryForm.cs

using System;

using System.Drawing;

using System.Windows.Forms;

namespace TurFirm

{

// Форма для написания и выполнения запросов к базе данных.

public partial class QueryForm: Form

{

// Экземпляр формы.

public static QueryForm Instance { get; private set; }

// Кнопка, которая отвечает за экземпляр формы.

public static Button InstanceButton { get; private set; }

public QueryForm(Button instanceButton)

{

InitializeComponent();

Instance = this;

InstanceButton = instanceButton;

}

private void QueryForm_Load(object sender, EventArgs e)

{

ControlBox = false;

WindowState = FormWindowState.Maximized;

}

private void QueryForm_Enter(object sender, EventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.LightBlue);

}

private void QueryForm_Deactivate(object sender, EventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.Empty);

}

private void QueryForm_FormClosed(object sender, FormClosedEventArgs e)

{

InstanceButton.SetFlatButtonColor(Color.Empty);

InstanceButton = null;

Instance = null;

}

private void btnUndo_Click(object sender, EventArgs e)

{

rtbQueryText.Undo();

}

private void btnRedo_Click(object sender, EventArgs e)

{

rtbQueryText.Redo();

}

private void btnErase_Click(object sender, EventArgs e)

{

rtbQueryText.ResetText();

}

private void btnZoomIn_Click(object sender, EventArgs e)

{

if (rtbQueryText.ZoomFactor < 3f)

rtbQueryText.ZoomFactor += 0.25f;

}

private void btnZoomOut_Click(object sender, EventArgs e)

{

if (rtbQueryText.ZoomFactor > 0.75f)

rtbQueryText.ZoomFactor -= 0.25f;

}

private void btnExecute_Click(object sender, EventArgs e)

{

try

{

dgvQuery.DataSource = OleDbPackage.ExecuteTable(rtbQueryText.Text);

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

}

private void rtbQueryText_TextChanged(object sender, EventArgs e)

{

dgvQuery.DataSource = null;

}

Файл ClientsForm.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Data.OleDb;

using System.Reflection;

using Microsoft.Office.Interop;

using Word = Microsoft.Office.Interop.Word;//Необхдимо добавить

using Excel = Microsoft.Office.Interop.Excel;

namespace TurFirm

{

public partial class ClientsForm: Form, IUpdateForm

{

OleDbConnection connection;

OleDbCommand command;

MainForm mainForm; // посилання на об'єкт головної форми

DataSet dataSet;

OleDbDataAdapter dataAdapter;

WorkerSearchForm searchForm; // форма для пошуку

public WorkerForm(OleDbConnection _connection, MainForm _mainForm)

{

InitializeComponent();

this.connection = _connection;

this.mainForm = _mainForm;

}

private void ClientsForm_Load(object sender, EventArgs e)

{

bool isOk = true; // флаг, чи успішно виконалися запити

mainForm.OpenedFormCollection.Add(this);

dataSet = new DataSet();

command = new OleDbCommand();

command.Connection = connection;

dataAdapter = new OleDbDataAdapter();

dataAdapter.SelectCommand = command;

try

{

connection.Open();

command.CommandText = "SELECT * FROM Vedomstva";

dataAdapter.Fill(dataSet, "Vedomstva");

command.CommandText = "SELECT * FROM Clients";

dataAdapter.Fill(dataSet, "Clients");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (!isOk)

this.Close();

bindingSource.DataSource = dataSet.Tables["Worker"]; // прив'язуємо BindingSource до таблиці

dgvWorker.DataSource = bindingSource; // прив'язуємо DataGridView до BindingSource

dgvWorker.Columns[0].ReadOnly = true; // перше поле є лічильником, тому його не можна редагувати

// Прив'язуємо усі елементи, що відповідають осередкам таблиці, до BindingSource

tbFIO.DataBindings.Add("Text", bindingSource, "FIO");

dtpBirthday.DataBindings.Add("Text", bindingSource, "Birthday");

cbPol.DataBindings.Add("Text", bindingSource, "Pol");

cbOtdel.DataSource = dataSet.Tables["Vedomstva"];

cbOtdel.DisplayMember = cbOtdel.ValueMember = "№_Otdel";

cbOtdel.DataBindings.Add("Text", bindingSource, "Otdel");

cbDolgnost.DataBindings.Add("Text", bindingSource, "Dolgnost");

tbZarplata.DataBindings.Add("Text", bindingSource, "Zarplata");

tbPassport.DataBindings.Add("Text", bindingSource, "Passport");

tbPhone.DataBindings.Add("Text", bindingSource, "Phone");

tbAdress.DataBindings.Add("Text", bindingSource, "Adress");

// Даємо полям таблиці українські назви

dgvWorker.Columns["№"].HeaderText = "Номер працівника";

dgvWorker.Columns["FIO"].HeaderText = "ПІБ працівника";

dgvWorker.Columns["Birthday"].HeaderText = "Дата народження";

dgvWorker.Columns["Pol"].HeaderText = "Стать";

dgvWorker.Columns["Otdel"].HeaderText = "Номер відділу";

dgvWorker.Columns["Dolgnost"].HeaderText = "Посада";

dgvWorker.Columns["Zarplata"].HeaderText = "Зарплата";

dgvWorker.Columns["Passport"].HeaderText = "Паспорт";

dgvWorker.Columns["Phone"].HeaderText = "Телефон";

dgvWorker.Columns["Adress"].HeaderText = "Адреса";

}

private void WorkerForm_FormClosed(object sender, FormClosedEventArgs e)

{

mainForm.OpenedFormCollection.Remove(this);

if (searchForm != null)

searchForm.Close(); // якщо форма для пошуку активована, закриваємо її

}

private void tsbSave_Click(object sender, EventArgs e)

{

if (!AreThereChanges())

return;

SaveChanges();

// Оновлюємо дані у формах

mainForm.OpenedFormCollection.UpdateAll();

}

private void tsbExcel_Click(object sender, EventArgs e)

{

object ms = Missing.Value;

Excel.Application app = new Excel.Application();

app.Visible = true;

//Створення нового документу

Excel.Workbook book = app.Workbooks.Add();

Excel.Worksheet sheet = book.Worksheets[1];

sheet.Range["A1"].Value = "Таблиця <Працывники>";

//Вывод названий колонок таблицы

for (int j = 0; j < dataSet.Tables["Worker"].Columns.Count; j++)

{

sheet.Cells[3, j + 1] = dataSet.Tables["Worker"].Columns[j].ColumnName.ToString();

}

//Вывод содержимого таблицы

for (int i = 0; i < dataSet.Tables["Worker"].Rows.Count; i++)

{

for (int j = 0; j < dataSet.Tables["Worker"].Columns.Count; j++)

{

sheet.Cells[i + 4, j + 1] = dataSet.Tables["Worker"].Rows[i][j].ToString();

}

sheet.get_Range("A1:E1").MergeCells = true;//Слияние ячеек

sheet.get_Range("A1:E1").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//Выравнивание

sheet.get_Range("A1:E1").Font.Size = 24;//Размер

sheet.get_Range("A1:E1").Font.Color = Color.Red;

}

private void tsbWord_Click(object sender, EventArgs e)

{

object ms = Missing.Value;

//Створення додатку Word

Word.Application app = new Word.Application();

app.Visible = true;

//Створення нового документу

Word.Document doc = app.Documents.Add(ref ms, ref ms, ref ms, ref ms);

doc.Activate(); //Активація документу

doc.ActiveWindow.Selection.Font.Color = Word.WdColor.wdColorRed;

doc.ActiveWindow.Selection.Font.Size = 16;

doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

doc.ActiveWindow.Selection.TypeText("Таблиця <Працівники>"); //Додавання тексту до документу

doc.Application.Selection.TypeParagraph(); //Перехід на новій рядок

doc.ActiveWindow.Selection.Font.Color = Word.WdColor.wdColorBlack;

doc.ActiveWindow.Selection.Font.Size = 12;

Word.Table table = doc.Tables.Add(doc.Application.Selection.Range, dataSet.Tables["Worker"].Rows.Count + 1, dataSet.Tables["Worker"].Columns.Count, ref ms, ref ms);

//Вывод названий колонок таблицы

for (int j = 0; j < dataSet.Tables["Worker"].Columns.Count; j++)

{

table.Cell(1, j + 1).Range.Text = dataSet.Tables["Worker"].Columns[j].ColumnName.ToString();

}

//Вывод записей таблицы

for (int i = 0; i < dataSet.Tables["Worker"].Rows.Count; i++)

{

for (int j = 0; j < dataSet.Tables["Worker"].Columns.Count; j++)

{

table.Cell(i + 2, j + 1).Range.Text = dataSet.Tables["Worker"].Rows[i][j].ToString();

}

//Вихід за межи таблиці

object o1 = Word.WdUnits.wdLine;

object o2 = 25;

doc.Application.Selection.MoveDown(ref o1, ref o2, ref ms);

}

private void tsbSearch_Click(object sender, EventArgs e)

{

if (searchForm == null)

{

searchForm = new WorkerSearchForm(dataSet.Tables["Worker"]);

searchForm.FormClosed += new FormClosedEventHandler(WorkerSearchForm_FormClosed); /* присвоюємо обробник на

* закриття форми пошуку */

searchForm.SearchResult += new WorkerSearchForm.SearchButtonClick(EndOfSearch); /* присвоюємо обробник на

* натискання кнопки пошуку */

searchForm.MdiParent = mainForm;

searchForm.Show();

}

else

searchForm.Focus();

}

private void WorkerSearchForm_FormClosed(object sender, FormClosedEventArgs e)

{

searchForm = null; // коли форма пошуку закрилася, посилання searchForm має вказувати на null

}

private void EndOfSearch(int rowIndex) // виділяє шуканий рядок у DataGridView

{

if (rowIndex != -1) // якщо пошук був вдалим, виділяємо шуканий рядок

{

dgvWorker.CurrentCell = dgvWorker.Rows[rowIndex].Cells[0];

this.Focus();

}

else

{

MessageBox.Show("Вибачте, але трапилася якась помилка.", searchForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

}

private void tsbClose_Click(object sender, EventArgs e)

{

this.Close();

}

private void btnOK_Click(object sender, EventArgs e)

{

bindingSource.EndEdit(); // завершуємо редагування, якщо воно відбувалося

}

private bool AreThereChanges() // повертає true, якщо були внесені зміни

{

DataTable dtChanges; // таблиця, що містить змінені записи

bindingSource.EndEdit(); // завершуємо редагування, якщо воно відбувалося

dgvWorker.EndEdit();

dtChanges = dataSet.Tables["Worker"].GetChanges();

return dtChanges == null ? false: true;

}

private void SaveChanges() // зберігає внесені зміни

{

try

{

connection.Open();

command.CommandText = "SELECT * FROM Worker";

OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);

dataAdapter.Update(dataSet.Tables["Worker"]);

dataSet.Tables["Worker"].AcceptChanges();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

public void UpdateForm()

{

bool isOk = true; // флаг, чи успішно виконалися запити

if (AreThereChanges())

{

// Якщо є внесені зміни і користувач бажає їх зберегти

if (MessageBox.Show("Зберегти внесені зміни?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)

== System.Windows.Forms.DialogResult.Yes)

{

SaveChanges();

}

// Оновлюємо дані у формі

dataSet.Tables["Vedomstva"].Clear();

dataSet.Tables["Worker"].Clear();

try

{

connection.Open();

command.CommandText = "SELECT * FROM Vedomstva";

dataAdapter.Fill(dataSet, "Vedomstva");

command.CommandText = "SELECT * FROM Worker";

dataAdapter.Fill(dataSet, "Worker");

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

isOk = false;

}

finally

{

if (connection.State == ConnectionState.Open)

connection.Close();

}

if (!isOk)

this.Close();

}

private void WorkerForm_FormClosing(object sender, FormClosingEventArgs e)

{

// Якщо зміни не були внесені, виходимо

if (!AreThereChanges())

return;

// Якщо користувач не бажає зберігати зміни, виходимо

if (MessageBox.Show("Зберегти внесені зміни?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)

== System.Windows.Forms.DialogResult.No)

return;

// Зберігаємо внесені зміни

tsbSave.PerformClick();

}

Файл QueryForm.Designer.cs

namespace TurFirm

{

partial class QueryForm

{

/// <summary>

/// Required designer variable.


Подобные документы

  • Побудова інформаційної системи "Магазин товарів для настільного тенісу" з автоматизації роботи магазину. Концептуальне моделювання бази даних. Обґрунтування вибору СУБД. Логічне проектування бази даних. Схема бази даних. Створення таблиць в конструкторі.

    курсовая работа [8,8 M], добавлен 16.12.2015

  • Побудування інформаційної концептуальної моделі дошкільного навчального закладу. Визначення ідентифікуючого набора атрибутів інформаційної системи. Відомості про структуру програми, мова програмування. Код створення бази даних на мові Transact-SQL.

    курсовая работа [433,7 K], добавлен 27.03.2016

  • Проектування інформаційної системи; концептуальне (інфологічне) проектування, побудова ER-діаграми, нормалізація даних. Даталогічне проектування баз даних, фізичне проектування інформаційних систем. СУБД Access: об'єкти, створення таблиць, запитів, форм.

    курсовая работа [13,9 M], добавлен 09.01.2010

  • Створення бази даних та робота з нею у програмному забезпеченні Microsoft Access. Проектування форм для зручного заповнення таблиць, звітів для відображення даних та їх друку, кнопкової форми, яка потрібна для зручної навігації між функціями бази даних.

    курсовая работа [1,3 M], добавлен 04.10.2014

  • Різновиди архітектур баз даних. Архітектура "файл-сервер" і локальні бази даних. Обґрунтування вибору архітектури стосовно проектованої системи. Основні концепції мови SQL. Структура запитів до окремих таблиць. Інтерфейс користувача проектованої системи.

    дипломная работа [972,5 K], добавлен 26.10.2012

  • Аналіз предметної галузі, постановка задачі, проектування бази даних. UML-моделювання, побудова ER-діаграми, схеми реляційної бази даних у третій нормальній формі. Призначення і логічна структура. Опис фізичної моделі бази даних, програмної реалізації.

    курсовая работа [3,5 M], добавлен 28.11.2011

  • Методика та основні етапи проектування інформаційної системи "Меблевий салон", опис необхідних для цього даних і джерела їх отримання. Побудова ER-діаграми та порядок її нормалізації. Методи створення таблиць та форм, можливості їх змін, редагування.

    курсовая работа [2,1 M], добавлен 08.12.2009

  • Проектування бази даних предметної області "Магазин будівельних матеріалів". Аналіз сукупності вхідних і вихідних даних, шляхи удосконалення інформаційної системи обліку товару. Організація інформаційної бази, розробка логічної і фізичної моделі.

    курсовая работа [559,2 K], добавлен 09.05.2016

  • Визначення мети створення бази даних магазину та таблиць, які вона повинна містити. Розгляд видів полів та ключів таблиць. Створення запитів, форм, звітів, макросів та модулів. Вибір системи управління базами даних. Реалізація моделі у Microsoft Access.

    курсовая работа [3,8 M], добавлен 20.07.2014

  • Проектування бази даних (БД). Проектування логічної моделі БД. Реалізація БД та створення таблиць. Встановлення зв’язків, вибір мови та середовища програмування. Опис функціональних елементів та реалізація програми. Опис та тестовий приклад програми.

    дипломная работа [1,6 M], добавлен 07.01.2017

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.