рис.2
2. Создание таблицы с помощью дизайнера VS 2005
Добавление столбцов
341
рис.3
Добавление через свойство Columns. Изменение свойств столбцов.
рис.4
342
Типы столбцов:
рис.5
Таблица создается следующей строкой:
DataGridView dataGridView1 = new DataGridView();
Добавление строк |
|
|
|
|
Через массивы row: |
|
|
|
|
string[] row0 = { "Xerox", "3120", |
"Лазерный", |
"Да", |
"256" }; |
string[] row1 = { "HP", "2110", |
"Лазерный", |
"Да", |
"1024" }; |
string[] row2 = { "Epson", "1423", |
"Струйный", |
"Нет", |
"1" }; |
dataGridView1.Rows.Add(row0); |
|
|
|
DataGridViewRowCollection rows = dataGridView1.Rows; |
rows.Add(row1); |
|
|
|
|
rows.Add(row2); |
|
|
|
|
dataGridView1.RowCount = 2; |
// добавить 2 пустые строки |
dataGridView1.Rows.Add(); |
// добавить пустую строку |
dataGridView1.Rows.Add(3); |
// добавить 3 пустые строки |
Через перечень строк:
dataGridView1.Rows.Add ("HP", "2110", "Лазерный", "Да", "16");
Удаление строк
Строка 0:
DataGridViewRow dstr = dataGridView1.Rows[0]; dataGridView1.Rows.Remove(dstr);
Текущая строка:
DataGridViewRow dstr = dataGridView1.CurrentRow; dataGridView1.Rows.Remove(dstr);
Все строки: dataGridView1.Rows.Clear();
Обработчики событий
● Обработчик события «щелчок на ячейке»:
dataGridView1_CellContentClick (object sender, DataGridViewCellEventArgs e)
Свойства: e.ColumnIndex |
- индекс столбца с акт. ячейкой, Y. |
e.RowIndex |
- индекс строки с акт. ячейкой, Х. |
● Обработчик события «изменение текущей активной ячейки»:
dataGridView1_CurrentCellChanged (object sender, EventArgs e)
Работа с ячейками
DataGridViewCell actCell = dataGridView1.CurrentCell;
Свойство Value – получить или изменить значение текущей активной ячейки (get и set).
actCell.Value – содержимое акт. ячейки.
int |
y = |
actCell.ColumnIndex; |
// индекс столбца |
int |
x = |
actCell.RowIndex; |
// индекс строки |
|
|
Point |
|
int |
y = |
dataGridView1.CurrentCellAddress.Y; |
// индекс столбца |
int |
x = |
dataGridView1.CurrentCellAddress.X; |
// индекс строки |
str = dataGridView1[x, y].Value; |
// на чтение |
dataGridView1[x, y].Value = "Лазерный"; |
// на запись |
str =dataGridView1.Rows[3].Cells[1].Value;
В обработчике CellContentClick:
str = dataGridView1 [e.ColumnIndex, e.RowIndex].Value;
3. Создание таблицы вручную
Структура таблицы DataGridView
Создание таблицы (сетки):
DataGridView dataGridView1 |
= new DataGridView(); |
|
|
|
|
рис.6 |
|
|
|
|
|
|
|
dataGridView1.Columns [0] или Columns ["Column1"] |
|
|
|
|
|
dataGridView1.Columns [1] |
|
|
|
|
|
dataGridView1.Columns [2] |
|
|
|
|
|
|
|
Столбцы - объекты класса |
|
|
|
Таблица - объект класса |
|
DataGridViewColumn |
|
|
|
DataGridView |
|
|
|
|
|
|
|
|
|
|
|
|
DataGridViewColumnCollection |
|
Name = Column1 |
|
|
|
|
HeaderText = "Поле-1" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Column2 |
|
|
|
|
|
|
"Поле-2" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Column3 "Поле-3"
dataGridView1.Columns
объект класса: DataGridViewTextBoxColumn DataGridViewComboBoxColumn DataGridViewCheckBoxColumn
. . . |
|
|
dataGridView1.Columns. |
AddRange(...) |
|
dataGridView1.Columns. |
Add(...) |
рис.7
|
|
|
|
|
|
|
|
|
dataGridView1.Rows[0] |
|
|
|
|
|
|
|
|
|
|
dataGridView1. Rows[1] |
|
|
|
|
Строки - объекты класса |
|
dataGridView1. Rows[2] |
|
|
|
|
|
|
|
|
|
DataGridViewRow |
|
|
|
Таблица - объект класса |
|
|
|
|
|
|
|
|
|
|
y: |
0 |
1 |
2 |
|
|
|
|
DataGridView |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
х: 0 |
|
A0 |
|
B0 |
|
C0 |
|
|
|
|
|
|
1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
A1 |
|
B1 |
C1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
|
A2 |
|
B2 |
C2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
A3 |
|
B3 |
C3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
dataGridView1 [3, 1].Value --или-- |
|
|
|
|
|
|
|
|
|
|
dataGridView1.Rows. Add (...) |
|
dataGridView1.Rows[3].Cells[1].Value |
|
|
|
|
|
|
|
|
|
|
|
|
dataGridView1.CurrentCellAddress.X;
dataGridView1.CurrentCellAddress.Y;
рис.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)
346
Способ 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
DataGridViewRowCollection.Add ()
DataGridViewRowCollection.Add
(DataGridViewRow)
DataGridViewRowCollection.Add
(Int32)
DataGridViewRowCollection.Add
(Object[])
Description
Adds a new row to the collection.
Adds the specified DataGridViewRow to the collection.
Adds the specified number of new rows to the collection.
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));
}