Создание таблицы вручную

  • docx
  • 18.11.2021
Публикация на сайте для учителей

Публикация педагогических разработок

Бесплатное участие. Свидетельство автора сразу.
Мгновенные 10 документов в портфолио.

Иконка файла материала Л2-002225.docx

Создание таблицы вручную

Структура таблицы DataGridView Создание таблицы (сетки):

DataGridView                 dataGridView1             = new DataGridView();


рис.6


рис.7


A3

 

 

 

 

 

 

 

 

A0

B0

C0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

рис.8

Добавление столбцов

Предварительное создание столбцов как самостоятельных объектов типа DataGridViewColumn.

Столбцы предварительно не создаются.

 

Способ 1.

DataGridViewTextBoxColumn марка = new DataGridViewTextBoxColumn();

 

DataGridViewTextBoxColumn модель = new DataGridViewTextBoxColumn();

. . . . . . . . . . .

 

Добавление столбцов в dataGridView1:

 

dataGridView1.Columns.Add(марка);

марка.HeaderText = "Марка";

 

dataGridView1.Columns.Add(модель);

модель.HeaderText = " Модель";

 

dataGridView1.Columns.AddRange((new DataGridViewColumn[] { марка, модель, тип, поддержкаUSB, количество_цветов });

 

Вставка столбца column2 после второго столбца, то есть с индексом

2.

 

dataGridView1.Columns.Insert (2, column2)


Способ 2.

Создание            и   добавление   DataGridViewTextBoxColumn-столбцов     (имя столбца, заголовок столбца):

dataGridView1.Columns.Add("марка", "Марка");

 

dataGridView1.Columns.Add("модель", "Модель");

Примечание. Имя ссылки на объект-столбец неизвестно.

 

Создание и добавление DataGridViewTextBoxColumn-столбцов без имени:

dataGridView1.Columns.Add ("", "Марка"); // заголовок

 

dataGridView1.Columns.Add ("", "Модель");

Примечание. Ссылка на объект-столбец неизвестна.

 

Создание и добавление DataGridViewTextBoxColumn-столбцов           без имени и заголовка:

 

dataGridView1.ColumnCount = 4;                                   // вставка 4-х столбцов

 

Установление свойств добавленных столбцов. Доступ к столбцу по его индексу:

 

dataGridView1.Columns[0].Name = "New0";                             // имя столбца

dataGridView1.Columns[1].Name = "New1";                             // имя столбца

 

dataGridView1.Columns[0].HeaderText = "HeadNew0"; // заголовок

dataGridView1.Columns[1].HeaderText = "HeadNew1"; // заголовок

 

Примечание. Если заголовок не задан, то в качестве заголовка столб- ца используется его имя.

 

Другие свойства столбца Доступ к столбцу по его имени:

 

dataGridView1.Columns ["имя"].DisplayIndex = 3; //Место столбца

dataGridView1. Columns.Clear();                   // Удалить все столбцы и строки

 

Наклонный стандартный шрифт:

dataGridView1.Columns[1].DefaultCellStyle.Font = new

Font(DataGridView.DefaultFont, FontStyle.Italic);

 

Значения в ячейках в центре по середине:

 

dataGridView1.Columns[1].DefaultCellStyle.Aligment =

DataGridViewContent Aligment.MiddleCenter; марка.ReadOnly = true; // Разрешить изменение ячейки Добавление строк

4-е перегруженных метода:


Name

Description

DataGridViewRowCollection.Add ()

Adds a new row to the collection.

DataGridViewRowCollection.Add (DataGridViewRow)

Adds                 the            specified

DataGridViewRow to the collection.

DataGridViewRowCollection.Add (Int32)

Adds the specified number of new rows to the collection.

DataGridViewRowCollection.Add (Object[])

Adds a new row to the collection, and populates the cells with the specified objects.

 

Способы добавления строк были рассмотрены выше!

 

Пример.

База принтеров. Программа только отображает строки. Ячейки дос- тупны только на чтение.


рис.9

-- Файл Printer.cs

using System;

using System.Collections.Generic; using System.Text;

using System.Collections;

 

namespace Printer_Virtual

{


class Printer

{

protected string[] str = new string[5]; // информация о принтере

private                           string    mark, model;

 

public Printer(string mark, string model)

{

this.mark = mark; this.model = model;

}

 

public virtual string[] Show()

{

str[0] = mark; str[1] = model; return str;

}

}

 

 

class LaserPrinter : Printer

{

string type = "Лазерный", USBsupport; int                                SupportedColors;

 

public LaserPrinter(string mark, string model,

string USBsupport, int SupportedColors)

: base(mark, model)

{

this.USBsupport = USBsupport; this.SupportedColors = SupportedColors;

}

 

public override string[] Show()

{

base.Show(); str[2] = type;

str[3] = USBsupport;

str[4] = SupportedColors.ToString(); return str;

}

}

 

 

class InkJetPrinter : Printer

{

string type = "Струйный", USBsupport; int SupportedColors;

 

public InkJetPrinter(string mark, string model,

string USBsupport, int SupportedColors)

: base(mark, model)

{

this.USBsupport = USBsupport;


this.SupportedColors = SupportedColors;

}

 

public override string[] Show()

{

base.Show(); str[2] = type;

str[3] = USBsupport;

str[4] = SupportedColors.ToString(); return str;

}

}

}

 

--Файл Form1.cs—

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data;

using System.Drawing; using System.Text;

using System.Windows.Forms; using System.Collections;

 

namespace Printer_Virtual

{

public partial class Form1 : Form

{

ArrayList obj = new ArrayList();                                      // Массив ссылок на объекты

 

public Form1()

{ InitializeComponent(); }

 

private void button1_Click(object sender, EventArgs e)                           // записать в obj

{

Printer printer; try

{

string ucb;

if (domainUpDownUSB.Text == "Да") ucb = "true";

else

ucb = "false";

 

if (domainUpDownType.Text == "Струйный")

 

printer = new InkJetPrinter(textBoxMark.Text, textBoxModel.Text,

ucb, int.Parse(textBoxColors.Text));

else

printer = new LaserPrinter(textBoxMark.Text, textBoxModel.Text,

ucb, int.Parse(textBoxColors.Text));

}


catch

{

MessageBox.Show("Заполнены не все поля " +

"или введен неверный тип данных!");

return;

}

 

obj.Add(printer);

label7.Text = obj.Count.ToString();

}

 

 

private void button2_Click(object sender, EventArgs e)                           // в таблицу

{

dataGridView1.Rows.Clear();

 

foreach (object prn in obj)

{

dataGridView1.Rows.Add ( ((Printer)prn).Show() );

}

}

 

 

private void выходToolStripMenuItem1_Click(object sender, EventArgs e)

{

Close();

}

 

 

private void button3_Click(object sender, EventArgs e)                            // очистка базы

{

obj.Clear(); dataGridView1.Rows.Clear(); label7.Text = obj.Count.ToString();

}

 

 

private void очиститьПоляToolStripMenuItem_Click(object sender,

EventArgs e)

{

textBoxMark.Clear(); textBoxModel.Clear(); textBoxColors.Clear();

}

 

 

private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)

{

MessageBox.Show("Программа 'База данных принтеров'.\n" + "Авторы: Горелов, Мошаров.");

}


private void помощьToolStripMenuItem1_Click(object sender, EventArgs e)

{

MessageBox.Show("Программа 'База данных принтеров'.\n" + "Ввод данных производится в специально отведенные поля.\n" + "Типы данных ввода:\n   Марка - строка\n   Модель - строка\n" + " Количество цветов - число.\n" +

"После ввода информации о принтере в БД, выводите ее в таблицу.");

}

}

}

 

-- Файл Form1.Designer.cs --

 

namespace Printer_Virtual

{

partial class Form1

{

private System.ComponentModel.IContainer components = null;

 

protected override void Dispose(bool disposing)

{

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

{

components.Dispose();

}

base.Dispose(disposing);

}

 

private void InitializeComponent()

{

this.textBoxMark = new System.Windows.Forms.TextBox(); this.textBoxModel = new System.Windows.Forms.TextBox(); this.textBoxColors = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button();

this.domainUpDownType = new System.Windows.Forms.DomainUpDown(); this.button2 = new System.Windows.Forms.Button(); this.domainUpDownUSB = new System.Windows.Forms.DomainUpDown(); this.button3 = new System.Windows.Forms.Button();

this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.menuStrip1 = new System.Windows.Forms.MenuStrip();

this.выходToolStripMenuItem                                                  =                        new                        Sys- tem.Windows.Forms.ToolStripMenuItem();

this.очиститьПоляToolStripMenuItem                                             =                   new                   Sys- tem.Windows.Forms.ToolStripMenuItem();

this.выходToolStripMenuItem1                                                 =                       new                       Sys- tem.Windows.Forms.ToolStripMenuItem();


this.помощьToolStripMenuItem

=

new

Sys-

tem.Windows.Forms.ToolStripMenuItem();

 

 

 

this.помощьToolStripMenuItem1

=

new

Sys-

tem.Windows.Forms.ToolStripMenuItem();

this.оПрограммеToolStripMenuItem                                              =                    new                    Sys- tem.Windows.Forms.ToolStripMenuItem();

this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.Марка = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Модель = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Тип = new System.Windows.Forms.DataGridViewTextBoxColumn();

this.ПоддержкаUSB                                                      =                             new                             Sys- tem.Windows.Forms.DataGridViewCheckBoxColumn();

this.Количество_цветов                                                    =                           new                           Sys- tem.Windows.Forms.DataGridViewTextBoxColumn();

this.groupBox1.SuspendLayout(); this.menuStrip1.SuspendLayout();

((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout();

//

// textBoxMark

//

this.textBoxMark.Location = new System.Drawing.Point(10, 43); this.textBoxMark.Name = "textBoxMark"; this.textBoxMark.Size = new System.Drawing.Size(100, 20); this.textBoxMark.TabIndex = 1;

//

// textBoxModel

//

this.textBoxModel.Location = new System.Drawing.Point(10, 86); this.textBoxModel.Name = "textBoxModel"; this.textBoxModel.Size = new System.Drawing.Size(100, 20); this.textBoxModel.TabIndex = 2;

//

// textBoxColors

//

this.textBoxColors.Location = new System.Drawing.Point(10, 130); this.textBoxColors.Name = "textBoxColors"; this.textBoxColors.Size = new System.Drawing.Size(100, 20); this.textBoxColors.TabIndex = 5;

//

// button1

//

this.button1.Location = new System.Drawing.Point(408, 68); this.button1.Name = "button1";

this.button1.Size = new System.Drawing.Size(99, 23); this.button1.TabIndex = 6;

this.button1.Text = "Ввести в базу"; this.button1.UseVisualStyleBackColor = true;

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// domainUpDownType

//

this.domainUpDownType.BackColor                                                           =                                  Sys- tem.Drawing.SystemColors.ActiveCaptionText;


this.domainUpDownType.Items.Add("Струйный"); this.domainUpDownType.Items.Add("Лазерный"); this.domainUpDownType.Location = new System.Drawing.Point(148, 87); this.domainUpDownType.Name = "domainUpDownType"; this.domainUpDownType.ReadOnly = true; this.domainUpDownType.Size = new System.Drawing.Size(73, 20); this.domainUpDownType.TabIndex = 8;

this.domainUpDownType.Text = "Струйный";

//

// button2

//

this.button2.Location = new System.Drawing.Point(408, 111); this.button2.Name = "button2";

this.button2.Size = new System.Drawing.Size(99, 23); this.button2.TabIndex = 9;

this.button2.Text = "Вывести базу"; this.button2.UseVisualStyleBackColor = true;

this.button2.Click += new System.EventHandler(this.button2_Click);

//

// domainUpDownUSB

//

this.domainUpDownUSB.BackColor                                                           =                                  Sys- tem.Drawing.SystemColors.ActiveCaptionText;

this.domainUpDownUSB.Items.Add("Да"); this.domainUpDownUSB.Items.Add("Нет"); this.domainUpDownUSB.Location = new System.Drawing.Point(148, 44); this.domainUpDownUSB.Name = "domainUpDownUSB"; this.domainUpDownUSB.ReadOnly = true;

this.domainUpDownUSB.Size = new System.Drawing.Size(73, 20); this.domainUpDownUSB.TabIndex = 10; this.domainUpDownUSB.Text = "Да";

//

// button3

//

this.button3.Location = new System.Drawing.Point(408, 155); this.button3.Name = "button3";

this.button3.Size = new System.Drawing.Size(99, 23); this.button3.TabIndex = 11;

this.button3.Text = "Очистить базу"; this.button3.UseVisualStyleBackColor = true;

this.button3.Click += new System.EventHandler(this.button3_Click);

//

// label1

//

this.label1.AutoSize = true;

this.label1.Location = new System.Drawing.Point(10, 27); this.label1.Name = "label1";

this.label1.Size = new System.Drawing.Size(43, 13); this.label1.TabIndex = 12;

this.label1.Text = "Марка:";

//

// label2

//

this.label2.AutoSize = true;


this.label2.Location = new System.Drawing.Point(10, 70); this.label2.Name = "label2";

this.label2.Size = new System.Drawing.Size(49, 13); this.label2.TabIndex = 13;

this.label2.Text = "Модель:";

//

// label3

//

this.label3.AutoSize = true;

this.label3.Location = new System.Drawing.Point(10, 117); this.label3.Name = "label3";

this.label3.Size = new System.Drawing.Size(82, 13); this.label3.TabIndex = 14;

this.label3.Text = "Кол-во цветов:";

//

// label4

//

this.label4.AutoSize = true;

this.label4.Location = new System.Drawing.Point(128, 27); this.label4.Name = "label4";

this.label4.Size = new System.Drawing.Size(93, 13); this.label4.TabIndex = 15;

this.label4.Text = "Поддержка USB:";

//

// label5

//

this.label5.AutoSize = true;

this.label5.Location = new System.Drawing.Point(128, 71); this.label5.Name = "label5";

this.label5.Size = new System.Drawing.Size(29, 13); this.label5.TabIndex = 16;

this.label5.Text = "Тип:";

//

// groupBox1

// this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1);

this.groupBox1.Controls.Add(this.domainUpDownUSB); this.groupBox1.Controls.Add(this.domainUpDownType); this.groupBox1.Controls.Add(this.textBoxColors); this.groupBox1.Controls.Add(this.textBoxModel); this.groupBox1.Controls.Add(this.textBoxMark); this.groupBox1.Location = new System.Drawing.Point(22, 27); this.groupBox1.Name = "groupBox1";

this.groupBox1.Size = new System.Drawing.Size(233, 193); this.groupBox1.TabIndex = 17;

this.groupBox1.TabStop = false; this.groupBox1.Text = "Ввод данных:";

//

// label6

//


this.label6.AutoSize = true;

this.label6.Location = new System.Drawing.Point(411, 207); this.label6.Name = "label6";

this.label6.Size = new System.Drawing.Size(96, 13); this.label6.TabIndex = 18;

this.label6.Text = "Объектов в базе:";

//

// label7

//

this.label7.AutoSize = true;

this.label7.Location = new System.Drawing.Point(507, 207); this.label7.Name = "label7";

this.label7.Size = new System.Drawing.Size(13, 13); this.label7.TabIndex = 19;

this.label7.Text = "0";

//

// label8

//

this.label8.AutoSize = true;

this.label8.Location = new System.Drawing.Point(19, 239); this.label8.Name = "label8";

this.label8.Size = new System.Drawing.Size(83, 13); this.label8.TabIndex = 20;

this.label8.Text = "Вывод данных:";

//

// menuStrip1

//

this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.выходToolStripMenuItem,

this.помощьToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1";

this.menuStrip1.RenderMode                                                                 =                                        Sys- tem.Windows.Forms.ToolStripRenderMode.System;

this.menuStrip1.Size = new System.Drawing.Size(568, 24); this.menuStrip1.TabIndex = 21;

this.menuStrip1.Text = "menuStrip1";

//

// выходToolStripMenuItem

// this.выходToolStripMenuItem.DropDownItems.AddRange(new

System.Windows.Forms.ToolStripItem[] { this.очиститьПоляToolStripMenuItem, this.выходToolStripMenuItem1});

this.выходToolStripMenuItem.Name = "выходToolStripMenuItem"; this.выходToolStripMenuItem.Size = new System.Drawing.Size(84, 20); this.выходToolStripMenuItem.Text = "Программа";

//

// очиститьПоляToolStripMenuItem

//

this.очиститьПоляToolStripMenuItem.Name                                   =         "очиститьПоляToolStrip- MenuItem";

this.очиститьПоляToolStripMenuItem.Size = new System.Drawing.Size(176, 22); this.очиститьПоляToolStripMenuItem.Text = "Очистить поля";


this.очиститьПоляToolStripMenuItem.ToolTipText = "Очистить поля ввода"; this.очиститьПоляToolStripMenuItem.Click += new

Sys- tem.EventHandler(this.очиститьПоляToolStripMenuItem_Click);

//

// выходToolStripMenuItem1

//

this.выходToolStripMenuItem1.Name = "выходToolStripMenuItem1"; this.выходToolStripMenuItem1.Size = new System.Drawing.Size(176, 22); this.выходToolStripMenuItem1.Text = "Выход"; this.выходToolStripMenuItem1.Click += new

Sys- tem.EventHandler(this.выходToolStripMenuItem1_Click);

//

// помощьToolStripMenuItem

// this.помощьToolStripMenuItem.DropDownItems.AddRange(new

System.Windows.Forms.ToolStripItem[] { this.помощьToolStripMenuItem1, this.оПрограммеToolStripMenuItem});

this.помощьToolStripMenuItem.Name = "помощьToolStripMenuItem"; this.помощьToolStripMenuItem.Size = new System.Drawing.Size(52, 20); this.помощьToolStripMenuItem.Text = "Инфо";

//

// помощьToolStripMenuItem1

//

this.помощьToolStripMenuItem1.Name = "помощьToolStripMenuItem1"; this.помощьToolStripMenuItem1.Size = new System.Drawing.Size(165, 22); this.помощьToolStripMenuItem1.Text = "Помощь"; this.помощьToolStripMenuItem1.Click += new

Sys- tem.EventHandler(this.помощьToolStripMenuItem1_Click);

//

// оПрограммеToolStripMenuItem

//

this.оПрограммеToolStripMenuItem.Name = "оПрограммеToolStripMenuItem"; this.оПрограммеToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.оПрограммеToolStripMenuItem.Text = "О программе"; this.оПрограммеToolStripMenuItem.Click += new

Sys- tem.EventHandler(this.оПрограммеToolStripMenuItem_Click);

//

// dataGridView1

//

this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToResizeColumns = false; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.BackgroundColor = System.Drawing.Color.White; this.dataGridView1.ColumnHeadersHeightSizeMode =

DataGridViewColumnHeadersHeight-

SizeMode.AutoSize;

this.dataGridView1.Columns.AddRange(new DataGridViewColumn[] { this.Марка,


this.Модель, this.Тип, this.ПоддержкаUSB,

this.Количество_цветов});

this.dataGridView1.Location = new System.Drawing.Point(12, 265); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(543, 239); this.dataGridView1.TabIndex = 22;

//

// Марка

//

this.Марка.HeaderText = "Марка"; this.Марка.Name = "Марка"; this.Марка.ReadOnly = true;

//

// Модель

//

this.Модель.HeaderText = "Модель"; this.Модель.Name = "Модель"; this.Модель.ReadOnly = true;

//

// Тип

//

this.Тип.HeaderText = "Тип"; this.Тип.Name = "Тип"; this.Тип.ReadOnly = true;

//

// ПоддержкаUSB

//

this.ПоддержкаUSB.HeaderText = "Поддержка USB"; this.ПоддержкаUSB.Name = "ПоддержкаUSB"; this.ПоддержкаUSB.ReadOnly = true;

this.ПоддержкаUSB.Resizable                                                                =                                       Sys- tem.Windows.Forms.DataGridViewTriState.True;

this.ПоддержкаUSB.SortMode = DataGridViewColumnSortMode.Automatic;

//

// Количество_цветов

//

this.Количество_цветов.HeaderText = "Количество Цветов"; this.Количество_цветов.Name = "Количество_цветов"; this.Количество_цветов.ReadOnly = true;

//

// Form1

//

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(568, 516); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.label8);

this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.groupBox1); this.Controls.Add(this.button3); this.Controls.Add(this.button2);


this.Controls.Add(this.button1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "Form1";

this.Text = "База данных \"Принтеры\""; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout();

((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false);

this.PerformLayout();

 

}

 

 

private System.Windows.Forms.TextBox textBoxMark; private System.Windows.Forms.TextBox textBoxModel; private System.Windows.Forms.TextBox textBoxColors; private System.Windows.Forms.Button button1;

private System.Windows.Forms.DomainUpDown domainUpDownType; private System.Windows.Forms.Button button2;

private System.Windows.Forms.DomainUpDown domainUpDownUSB; private System.Windows.Forms.Button button3;

private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5;

private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label6;

private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8;

private System.Windows.Forms.MenuStrip menuStrip1;

private System.Windows.Forms.ToolStripMenuItem выходToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem выходToolStripMenuItem1; private                                         System.Windows.Forms.ToolStripMenuItem         очиститьПоляToolStrip-

MenuItem;

private System.Windows.Forms.ToolStripMenuItem помощьToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem помощьToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem оПрограммеToolStripMenuItem; private System.Windows.Forms.DataGridView dataGridView1;

private System.Windows.Forms.DataGridViewTextBoxColumn Марка; private System.Windows.Forms.DataGridViewTextBoxColumn Модель; private System.Windows.Forms.DataGridViewTextBoxColumn Тип;

private System.Windows.Forms.DataGridViewCheckBoxColumn ПоддержкаUSB; private System.Windows.Forms.DataGridViewTextBoxColumn Количество_цветов;

}

}

 

Пример 2

 

Предметная область - сеть аэропортов, связанных авиатрассами Определить длину кратчайшего по количеству трасс маршрута


от заданного аэропорта до всех остальных аэропортов. Представление сети аэропортов - граф, заданный матрицей смежно-

сти.

Вершина графа - азропорт, ребро - авиатрасса.

Редактирование матрицы смежности - визуально щелчком мыши на соответствующей ячейке. Назначение аэропорта вылета - щелчком мыши на имени аэропорта в левой колонке таблицы.

 

Решение задачи основано на обходе графа в ширину. Управление обходом через очередь.

Роль окраски вершин при обходе выполняет массив расстояний.

Отрицательное значение расстояния эквивалентно не пройденной вершине.


рис.10

 

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data;

using System.Drawing; using System.Text;

using System.Windows.Forms; using System.Collections;

 

 

namespace EX1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 

string[] name;                                   //имена аэропортов

int                            n,         //Количество аэропортов

старт;                                    //порядковый номер аэропорта вылета

int[]                          d;         //Расстояние от аэропорта вылета до всех аэропортов


private void Расстояние(bool[,] матр)

{

int i;

int номаэропорт,расстояние; Queue очередь = new Queue(); очередь.Clear();

d = new int[n];

for(i=0; i<n; i++) d[i] = -1; d[старт] = 0;

очередь.Enqueue(старт);

 

while (очередь.Count != 0)

{

номаэропорт = (int)очередь.Dequeue();

расстояние = d[номаэропорт] + 1;

 

for (i = 0; i < n; i++)

if (матр[номаэропорт, i] && d[i] == -1)

{

d[i] = расстояние; очередь.Enqueue(i);

}

}

}

 

private void Form1_Load(object sender, EventArgs e)

{

name = new string[]

{ "Томск","Омск","Курган","Ачинск","Абакан",

"Тюмень","Тайга","Барнаул","Бийск","Бердск"};

}

 

private void Сеть_Click(object sender, EventArgs e)

{

n = (int)Количество.Value;

Трасса.Columns.Add("", "Аэропорт");

 

for(int i = 0; i < n; i++) Трасса.Columns.Add("", name[i]); for (int i = 0; i < n-1; i++) Трасса.Rows.Add();

for(int y = 0; y < n; y++) Трасса[0, y].Value = name[y];

 

for (int x = 1; x <=n; x++) for (int y = 0; y < n; y++)

Трасса[x, y].Value = " ";

}

 

 

private void Трасса_CurrentCellChanged(object sender, EventArgs e)

{

int x, y;


x = Трасса.CurrentCellAddress.X; y = Трасса.CurrentCellAddress.Y;

if (x < 0) return; if (x == 0)

{

старт = Трасса.CurrentCellAddress.Y; аэропортВылета.Text = name[старт]; return;

}

if (x == y + 1) return;

if ((string)(Трасса[x, y].Value) == " ")

{

Трасса[x, y].Value = "+";

Трасса[y + 1, x - 1].Value = "+";

}

else

{

Трасса[x, y].Value = " ";

Трасса[y + 1, x - 1].Value = " ";

}

}

private void Вычислить_Click(object sender, EventArgs e)

{

bool[,] матр = new bool[n, n]; int i,j;

for (i = 0; i < n; i++) for (j = 0; j < n; j++)

if ((string)(Трасса[j+1, i].Value) == "+")

матр[i, j] = true; else

матр[i, j] = false;

Расстояние(матр); for (i = 0; i < n; i++)

if(d[i]>=0)

Маршрут.Items.Add(name[i]+"("+d[i]+")"); else

Маршрут.Items.Add(name[i]+"(не долететь)");

}

 

 

private void Очистить_Click(object sender, EventArgs e)

{

Трасса.Columns.Clear(); Трасса.Rows.Clear(); Маршрут.Items.Clear();

}

 

 

private void ОчисткаМар_Click(object sender, EventArgs e)

{

Маршрут.Items.Clear();

}


}

}

 

 

using System;

using System.Collections.Generic; using System.Windows.Forms;

 

namespace EX1

{

static class Program

{

/// <summary>

/// The main entry point for the application.

/// </summary> [STAThread] static void Main()

{

Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());

}

}

}

 

 

 

 

namespace EX1

{

partial class Form1

{

private System.ComponentModel.IContainer components = null;

 

protected override void Dispose(bool disposing)

{

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

{

components.Dispose();

}

base.Dispose(disposing);

}

 

#region Windows Form Designer generated code

 

private void InitializeComponent()

{

DataGridViewCellStyle dataGridViewCellStyle3 = new

Sys- tem.Windows.Forms.DataGridViewCellStyle();

this.Трасса = new System.Windows.Forms.DataGridView();

 

this.Сеть = new System.Windows.Forms.Button();

this.Количество = new System.Windows.Forms.NumericUpDown();


this.Маршрут = new System.Windows.Forms.ListBox(); this.Вычислить = new System.Windows.Forms.Button(); this.Очистить = new System.Windows.Forms.Button(); this.ОчисткаМар = new System.Windows.Forms.Button(); this.аэропортВылета = new System.Windows.Forms.TextBox(); this.Вылет = new System.Windows.Forms.Label();

 

((System.ComponentModel.ISupportInitialize)(this.Трасса)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Количество)).BeginInit(); this.SuspendLayout();

//

// Трасса

//

dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;

dataGridViewCellStyle3.BackColor =

System.Drawing.Color.White; dataGridViewCellStyle3.Font = new System.Drawing.Font("Times New Roman",

12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle3.SelectionBackColor =

System.Drawing.Color.FromArgb(((int)(((byte)(255)))),

((int)(((byte)(255)))),

((int)(((byte)(192)))));

dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.Black; dataGridViewCellStyle3.WrapMode =

Sys- tem.Windows.Forms.DataGridViewTriState.True;

this.Трасса.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle3; this.Трасса.ColumnHeadersHeightSizeMode =

Sys- tem.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;

this.Трасса.Location = new System.Drawing.Point(12, 12); this.Трасса.Name = "Трасса"; this.Трасса.RowTemplate.DefaultCellStyle.Font = new

System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));

this.Трасса.RowTemplate.DefaultCellStyle.ForeColor =

Sys-

tem.Drawing.Color.Black;

this.Трасса.RowTemplate.DefaultCellStyle.SelectionBackColor =

System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));

this.Трасса.RowTemplate.DefaultCellStyle.SelectionForeColor =

Sys-

tem.Drawing.Color.Black;

this.Трасса.Size = new System.Drawing.Size(764, 221); this.Трасса.TabIndex = 0; this.Трасса.CurrentCellChanged += new

System.EventHandler(this.Трасса_CurrentCellChanged);


//

// Сеть

//

this.Сеть.Location = new System.Drawing.Point(149, 262); this.Сеть.Name = "Сеть";

this.Сеть.Size = new System.Drawing.Size(194, 23); this.Сеть.TabIndex = 1;

this.Сеть.Text = "Сформирвать сеть авиалиний"; this.Сеть.UseVisualStyleBackColor = true;

this.Сеть.Click += new System.EventHandler(this.Сеть_Click);

//

// Количество

//

this.Количество.Location = new System.Drawing.Point(12, 262); this.Количество.Maximum = new decimal(new int[] {

10,

0,

0,

0});

this.Количество.Minimum = new decimal(new int[] { 2,

0,

0,

0});

this.Количество.Name = "Количество"; this.Количество.Size = new System.Drawing.Size(120, 20); this.Количество.TabIndex = 2;

this.Количество.Value = new decimal(new int[] { 5,

0,

0,

0});

//

// Маршрут

//

this.Маршрут.FormattingEnabled = true; this.Маршрут.Location = new System.Drawing.Point(805, 12); this.Маршрут.Name = "Маршрут";

this.Маршрут.Size = new System.Drawing.Size(145, 225); this.Маршрут.TabIndex = 3;

//

// Вычислить

//

this.Вычислить.Location = new System.Drawing.Point(805, 259); this.Вычислить.Name = "Вычислить";

this.Вычислить.Size = new System.Drawing.Size(145, 23); this.Вычислить.TabIndex = 4;

this.Вычислить.Text = "Вычислить длину"; this.Вычислить.UseVisualStyleBackColor = true;

this.Вычислить.Click += new System.EventHandler(this.Вычислить_Click);

//

// Очистить

//

this.Очистить.Location = new System.Drawing.Point(655, 262);


this.Очистить.Name = "Очистить";

this.Очистить.Size = new System.Drawing.Size(121, 23); this.Очистить.TabIndex = 5;

this.Очистить.Text = "Очистить сеть"; this.Очистить.UseVisualStyleBackColor = true;

this.Очистить.Click += new System.EventHandler(this.Очистить_Click);

//

// ОчисткаМар

//

this.ОчисткаМар.Location = new System.Drawing.Point(805, 288); this.ОчисткаМар.Name = "ОчисткаМар";

this.ОчисткаМар.Size = new System.Drawing.Size(145, 23); this.ОчисткаМар.TabIndex = 6;

this.ОчисткаМар.Text = "Очистить результат"; this.ОчисткаМар.UseVisualStyleBackColor = true;

this.ОчисткаМар.Click += new System.EventHandler(this.ОчисткаМар_Click);

//

// аэропортВылета

//

this.аэропортВылета.Location = new System.Drawing.Point(12, 309); this.аэропортВылета.Name = "аэропортВылета"; this.аэропортВылета.Size = new System.Drawing.Size(120, 20); this.аэропортВылета.TabIndex = 7;

//

// Вылет

//

this.Вылет.AutoSize = true;

this.Вылет.Location = new System.Drawing.Point(163, 312); this.Вылет.Name = "Вылет";

this.Вылет.Size = new System.Drawing.Size(96, 13); this.Вылет.TabIndex = 8;

this.Вылет.Text = "Аэропорт вылета";

//

// Form1

//

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(962, 359); this.Controls.Add(this.Вылет); this.Controls.Add(this.аэропортВылета); this.Controls.Add(this.ОчисткаМар); this.Controls.Add(this.Очистить); this.Controls.Add(this.Вычислить); this.Controls.Add(this.Маршрут); this.Controls.Add(this.Количество);

this.Controls.Add(this.Сеть); this.Controls.Add(this.Трасса); this.Name = "Form1";

this.Text = "ВЫЧИСЛЕНИЕ ДЛИНЫ КРАТЧАЙШЕГО МАРШРУТА ОТ АЭ- РОПОРТА";

this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.Трасса)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Количество)).EndInit(); this.ResumeLayout(false);


рис.11this.PerformLayout();

 

}

 

#endregion

 

private System.Windows.Forms.DataGridView Трасса; private System.Windows.Forms.Button Сеть;

private System.Windows.Forms.NumericUpDown Количество; private System.Windows.Forms.ListBox Маршрут;

private System.Windows.Forms.Button Вычислить; private System.Windows.Forms.Button Очистить; private System.Windows.Forms.Button ОчисткаМар;

private System.Windows.Forms.TextBox аэропортВылета; private System.Windows.Forms.Label Вылет;

}

}

 

Обработчики событий:



 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

рис.12