Курсовой проект (548453), страница 4
Текст из файла (страница 4)
private void applayButton_Click(object sender, EventArgs e)
{
try
{
updateTables();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
/** Нажатие кнопки "Сохранить в XML" */
private void saveToXMLButton_Click(object sender, EventArgs e)
{
try
{
saveToXMLDialog.DefaultExt = "xml";
saveToXMLDialog.Filter = "XML files (*.xml)|*.xml|All files|*.*";
if (saveToXMLDialog.ShowDialog() == DialogResult.OK)
{
getDataTable().WriteXml(saveToXMLDialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// ---------- События формы -----------------------------------------------------
/** Обрабатывает загрзку формы. Вызывает заполнение наборов данных */
private void BaseFormEditor_Load(object sender, EventArgs e)
{
fillTables();
}
// ----------- Мои методы --------------------------------------------------------------
/** Инициализирует программу */
private void init()
{
// Выставляет имя
this.Text = getFormCaption();
this.MaximizeBox = true;
}
#region Windows Form Designer generated code
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
private void InitializeComponent()
{
// Создание новых компонентов
//
// MainDataSet
//
this.mainDataSet = new Mpei.Editors.mainDataSet();
((System.ComponentModel.ISupportInitialize)(this.mainDataSet)).BeginInit();
this.mainDataSet.DataSetName = "mainDataSet";
this.mainDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
((System.ComponentModel.ISupportInitialize)(this.mainDataSet)).EndInit();
this.components = new System.ComponentModel.Container();
this.controlPanel = new System.Windows.Forms.FlowLayoutPanel();
this.buttonPanel = new System.Windows.Forms.FlowLayoutPanel();
this.applayButton = new System.Windows.Forms.Button();
saveToXmlButton = new Button();
loadFromXmlButton = new Button();
getReportButton = new Button();
this.mainPanel = new System.Windows.Forms.Panel();
controlLabel = new Label();
this.buttonPanel.SuspendLayout();
this.mainPanel.SuspendLayout();
this.SuspendLayout();
// ---------- Инициализация таблицы ---------------------------------------------------
// Создание таблицы
mainGrid = new System.Windows.Forms.DataGridView();
// Признак начала иницаилизации
((System.ComponentModel.ISupportInitialize)(this.mainGrid)).BeginInit();
mainGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
mainGrid.Dock = System.Windows.Forms.DockStyle.Fill;
mainGrid.Location = new System.Drawing.Point(0, 0);
mainGrid.Name = "mainGrid";
mainGrid.Size = new System.Drawing.Size(492, 359);
mainGrid.TabIndex = 0;
mainGrid.ColumnHeadersHeight = 50;
// ---------- Инициализация связи с основным набором данных ----------------------------
// Создаем компонент привязки к данным
mainBindingSource = new System.Windows.Forms.BindingSource(this.components);
// Начало редактирования компонента
((System.ComponentModel.ISupportInitialize)(this.mainBindingSource)).BeginInit();
// Подключаем источник данных к таблице
mainGrid.DataSource = this.mainBindingSource;
// Полчаем имя основной таблицы для отображения
this.mainBindingSource.DataMember = getMainSourceName();
// Подключаем источник данных к набор данных
this.mainBindingSource.DataSource = this.mainDataSet;
// Заканчиваем редактирование компонента
((System.ComponentModel.ISupportInitialize)(mainBindingSource)).EndInit();
// Инициализируем таблицу
initDataTable();
// Создает набор конолонок. Подключает их к таблице
mainGrid.Columns.AddRange(this.getTableColumns());
// Признак конца инициализации
((System.ComponentModel.ISupportInitialize)(this.mainGrid)).EndInit();
/*Пропущен код инициализации контролов*/
}
#endregion
// ---------- Контролы ------------------------------------------------------
/** Таблица */
protected System.Windows.Forms.DataGridView mainGrid;
/** Главная панель (на ней пасполагается таблица */
protected Panel mainPanel;
/** Панель для кнопок */
private FlowLayoutPanel buttonPanel;
/** Панель для нижних контролов */
private FlowLayoutPanel controlPanel;
/** Кнопка применить */
private Button applayButton;
/** Кнопка сохранения данных таблицы в XML */
private Button saveToXmlButton;
/** Кнопка сохранения данных таблицы в XML */
private Button loadFromXmlButton;
/** Кнопка вывода отчета */
private Button getReportButton;
/** Строка состояний */
private Label controlLabel;
// ---------- Диалоги ------------------------------------------------------
private SaveFileDialog saveToXMLDialog;
// ---------- Переменные ---------------------------------------------------
/** Набор данных */
protected mainDataSet mainDataSet;
/** Связь с основной таблицей */
private System.Windows.Forms.BindingSource mainBindingSource;
/** Компонентная модель */
protected System.ComponentModel.IContainer components;
}
}
Класс для редактирования таблицы БД – Институты
(Приведем как пример, ибо остальные подобные классы аналогичны этому – все наследуются от базового класса)
namespace Mpei.Editors
{
class InstitutesEditor : BaseFormEditor
{
// ---------- Реализаця BaseFormEditor ---------------------------------------------
/** Возвращает данные таблицы */
protected override System.Data.DataTable getDataTable()
{
return institutesTableAdapter.GetData();
}
/** Сохраняет данные для всех таблиц. Должен быть перекрыт в потомках! */
protected override void updateTables()
{
institutesTableAdapter.Update(mainDataSet);
}
/** Возвращает заголовок формы */
protected override String getFormCaption()
{
return "Институты";
}
/** Заполняет таблицы данными */
protected override void fillTables()
{
this.institutesTableAdapter.Fill(this.mainDataSet.Institutes);
}
protected override String getMainSourceName()
{
return "Institutes";
}
protected override void initDataTable()
{
institutesTableAdapter = new Mpei.Editors.mainDataSetTableAdapters.InstitutesTableAdapter();
institutesTableAdapter.ClearBeforeFill = true;
}
/** Возвращает колонки таблицы */
protected override DataGridViewColumn[] getTableColumns()
{
DataGridViewColumn[] ret = new DataGridViewColumn[3];
// Institute_id
ret[0] = new DataGridViewTextBoxColumn();
ret[0].DataPropertyName = "institute_id";
ret[0].HeaderText = "institute_id";
ret[0].Name = "institute_id";
ret[0].ReadOnly = true;
ret[0].Visible = false;
// Institute_name
ret[1] = new DataGridViewTextBoxColumn();
ret[1].DataPropertyName = "institute_name";
ret[1].HeaderText = "Институт";
ret[1].Name = "institute_name";
// Institute_longname
ret[2] = new DataGridViewTextBoxColumn();
ret[2].DataPropertyName = "institute_longname";
ret[2].HeaderText = "Полное название";
ret[2].Name = "institute_longname";
return ret;
}
// ---------- Данные ---------------------------------------------------------------
// ---------- Адаптеры таблиц ------------------------------------------------------
private Mpei.Editors.mainDataSetTableAdapters.InstitutesTableAdapter institutesTableAdapter;
}
}
Список литературы
1. Практическое владение языком SQL. www.sql-ex.ru. [В Интернете]
2. С.В., Маклаков. ERwin и BPwin.
3. В.В., Лабор. Си Шарп. Создание приложений для Windows. Минск : Харвест, 2003.
4. Фаронов, Валерий. Программирование на языке C#.