Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lec

.pdf
Скачиваний:
41
Добавлен:
24.03.2015
Размер:
3.43 Mб
Скачать

public Person( string name, Sex sex, DateTime dob )

{

this.name = name; this.sex = sex; this.dateOfBirth = dob; numb = ++numbs;

}

// [Browsable(false)] public uint Numb

{

get { return numb; }

}

public string Name

{

get { return name; } set { name = value; }

}

public Sex Sex

{

get { return sex; } set { sex = value; }

}

public DateTime DateOfBirth

{

get { return dateOfBirth; } set { dateOfBirth = value; }

}

}

public enum Sex

{

муж, жен

}

using System;

using System.Collections;

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

using System.Drawing; using System.Text;

using System.Windows.Forms;

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

371

}

ArrayList people;

private void Form1_Load(object sender, EventArgs e)

{

// создадим массив объектов типа Person people = new ArrayList ();

people.Add (new Person("Иванов", Sex.муж, new DateTime(1980, 12, 14))); people.Add(new Person("Борисов", Sex.муж, new DateTime(1982, 10, 29))); people.Add (new Person("Симонов", Sex.муж, new DateTime(1965, 5, 17))); people.Add (new Person("Кидман", Sex.жен, new DateTime(1988, 1, 3)));

}

private void getData_Click(object sender, EventArgs e)

{

dataGridView1.AutoGenerateColumns = true;

dataGridView1.DataSource = people;

//Изменить имя столбца dataGridView1.Columns["Sex"].HeaderText = "Пол";

//установим последовательность столбцов в таблице

DataGridViewColumnCollection columns = dataGridView1.Columns; columns[0].DisplayIndex = 2;

columns[1].DisplayIndex = 3; columns[2].DisplayIndex = 0;

//другой способ выборки столбца (не путать Name со свойством таблицы) dataGridView1.Columns["Name"].DisplayIndex = 1;

}

private void Изменить_порядок_Click(object sender, EventArgs e)

{

MessageBox.Show(((Person)people[1]).Name); // старое значение ((Person)people[1]).Name = "aaaaaaa"; // новое значение имени

//изменение значения в массиве находит отражение в таблице

//перестановка столбцов dataGridView1.Columns["Numb"].DisplayIndex = 1; dataGridView1.Columns["Name"].DisplayIndex = 0; dataGridView1.Columns["Sex"].DisplayIndex = 3; dataGridView1.Columns["DateOfBirth"].DisplayIndex = 2;

}

}

Изменение значения ячейки в таблице приводит к изменению соответствующего элемента в массиве.

Изменяем “Борисов” на “Антонов”.

372

рис.15

Изменение элемента массива в программе

((Person)people[1]).Name = "aaaaaaa";

отображается в таблице.

рис.16

Порядок следования столбцов не всегда соответствует порядку следования свойств массива.

Примеры изменения порядка следования столбцов:

dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = people;

373

Способ 1. Использование числового индекса

dataGridView1.Columns[3].DisplayIndex = 3;

DataGridViewColumnCollection columns = dataGridView1.Columns; columns[0].DisplayIndex = 2;

columns[1].DisplayIndex = 1; columns[2].DisplayIndex = 0;

Способ 2. Использование имени столбца в качестве индекса

dataGridView1.Columns["Numb"].DisplayIndex = 1; dataGridView1.Columns["Name"].DisplayIndex = 0; dataGridView1.Columns["Sex"].DisplayIndex = 3; dataGridView1.Columns["DateOfBirth"].DisplayIndex = 2;

рис.17

Определение источника данных для столбца типа

DataGridViewComboBoxColumn

Комбинированный список является общим для всех ячеек столбца DataGridViewComboBoxColumn. Поэтому в качестве источника данных для такого столбца может использоваться массив объектов. Имя массива необходимо указать в свойстве DataSource столбца

DataGridViewComboBoxColumn.

Если объект массива содержит несколько открытых свойств, то необходимо в DisplayMember указать, какое свойство является отображаемым, а в ValueMember - какое свойство возвращает значение в программу. Свойство DataPropertyName указывает имя свойства в источнике данных таблицы, которое является индексом в списке.

374

рис.18

/* Пример определения источника данных для таблицы. * Столбцы строятся автоматически.

*/

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;

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

Item[] items;

private void getData_Click(object sender, EventArgs e)

{

// создать источник данных для таблицы items = new Item[4];

items[0] = new Item(0, false); items[1] = new Item(1, true); items[2] = new Item(2, false); items[3] = new Item(3, false);

// создать массив для списка

ArrayList arl = new ArrayList();

arl.Add (new ItemComboBox("aaa",0));

375

arl.Add (new ItemComboBox("bbb",1)); arl.Add (new ItemComboBox("ccc", 2)); arl.Add (new ItemComboBox("ddd",3));

dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = items; dataGridView1.Columns["Boolean"].HeaderText = "CheckBox";

{ // создание столбца – комбинированного списка

DataGridViewComboBoxColumn cbс = new DataGridViewComboBoxColumn();

cbс.HeaderText = "Список";

cbс.DataSource = arl;

// массив в качестве источника

cbс.DisplayMember = "TextCBox";

//из ItemComboBox !

cbс.ValueMember = "Value";

//из ItemComboBox !

//cbс.DataPropertyName = "TextBox";

//из Item !

// добавить комб. список к коллекции столбцов dataGridView1.Columns.Add(cbс);

}

protected class Item

{

private int textBox; private bool bolean;

public Item(int textBox, bool bolean)

{

this.textBox = textBox; this.bolean = bolean;

}

public int TextBox

{ get { return textBox; } }

public bool Boolean

{ get { return bolean; } }

}

protected class ItemComboBox

{

private string textCBox; private int value;

public ItemComboBox(string textCBox, int value)

{

this.textCBox = textCBox; this.value = value;

}

public string TextCBox

376

{ get { return textCBox; } }

public int Value

{ get { return value; } }

}

}

The DataGridViewComboBoxColumn class is a specialized type of DataGridViewColumn used to logically host cells that enable selection and editing. A DataGridViewComboBoxColumn has an associated DataGridViewComboBoxCell in every DataGridViewRow that intersects it.

The following steps describe a common way to use this class: Create a DataGridView.

Set the DataSource property of the DataGridView. Create a DataGridViewComboBoxColumn.

If the data source contains multiple properties or columns, set the DataPropertyName property to the name of the property or column for populating the cell values.

DataPropertyName - gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.

Use the DataSource or Items properties to establish the selections.

Use the ValueMember and DisplayMember properties to establish a mapping between cell values and what will be displayed on the screen.

The DataGridViewComboBoxColumn will only work properly if there is a mapping between all its cell values that are populated by the DataGridView.DataSource property and the range of choices populated either by the DataSource property or the Items property. If this mapping doesn't exist, the message "An Error happened Formatting, Display" will appear when the column is in view.

The default sort mode for this column type is NotSortable.

Notes to Inheritors When you derive from DataGridViewComboBoxColumn and add new properties to the derived class, be sure to override the Clone method to copy the new properties during cloning operations. You should also call the base class's Clone method so that the properties of the base class are copied to the new cell.

Дополнительные примеры: Example

The following code example demonstrates how to create an unbound DataGridView; set the ColumnHeadersVisible, ColumnHeadersDefaultCellStyle, and

ColumnCount properties; and use the Rows and Columns properties. It also demonstrates how to use a version of the AutoResizeColumnHeadersHeight and AutoResizeRows methods to properly size the column headers and the rows. To run this example, paste the following code into a form that contains a DataGridView named dataGridView1 and a button named Button1, and then call the InitializeDataGridView method from the form's constructor or Load event handler. Ensure all events are connected with their event handlers.

private void InitializeDataGridView()

{

// Create an unbound DataGridView by declaring a column count.

377

dataGridView1.ColumnCount = 4; dataGridView1.ColumnHeadersVisible = true;

// Set the column header style.

DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();

columnHeaderStyle.BackColor = Color.Beige; columnHeaderStyle.Font = new Font("Verdana", 10, FontStyle.Bold); dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;

//Set the column header names. dataGridView1.Columns[0].Name = "Recipe"; dataGridView1.Columns[1].Name = "Category"; dataGridView1.Columns[2].Name = "Main Ingredients"; dataGridView1.Columns[3].Name = "Rating";

//Populate the rows.

string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef", "**" };

string[] row2 = new string[] { "Key Lime Pie", "Dessert", "lime juice, evaporated milk", "****" };

string[] row3 = new string[] { "Orange-Salsa Pork Chops", "Main Dish", "pork chops, salsa, orange juice", "****" };

string[] row4 = new string[] { "Black Bean and Rice Salad", "Salad", "black beans, brown rice", "****" };

string[] row5 = new string[] { "Chocolate Cheesecake", "Dessert", "cream cheese", "***" };

string[] row6 = new string[] { "Black Bean Dip", "Appetizer", "black beans, sour cream", "***" };

object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

foreach (string[] rowArray in rows)

{

dataGridView1.Rows.Add(rowArray);

}

}

private void button1_Click(object sender, System.EventArgs e)

{

//Resize the height of the column headers. dataGridView1.AutoResizeColumnHeadersHeight();

//Resize all the row heights to fit the contents of all non-header cells. dataGridView1.AutoResizeRows(

DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);

}

private void InitializeContextMenu()

{

// Create the menu item.

ToolStripMenuItem getRecipe = new ToolStripMenuItem("Search for recipe", null, new System.EventHandler(ShortcutMenuClick));

378

//Add the menu item to the shortcut menu. ContextMenuStrip recipeMenu = new ContextMenuStrip(); recipeMenu.Items.Add(getRecipe);

//Set the shortcut menu for the first column. dataGridView1.Columns[0].ContextMenuStrip = recipeMenu; dataGridView1.MouseDown += new MouseEventHandler(dataGridView1_MouseDown);

}

private DataGridViewCell clickedCell;

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)

{

//If the user right-clicks a cell, store it for use by the shortcut menu. if (e.Button == MouseButtons.Right)

{

DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y); if (hit.Type == DataGridViewHitTestType.Cell)

{

clickedCell = dataGridView1.Rows[hit.RowIndex].Cells[hit.ColumnIndex];

}

}

}

private void ShortcutMenuClick(object sender, System.EventArgs e)

{

if (clickedCell != null)

{

//Retrieve the recipe name.

string recipeName = (string)clickedCell.Value;

//Search for the recipe. System.Diagnostics.Process.Start(

"http://search.msn.com/results.aspx?q=" + recipeName); //null);

}

}

379

СОЗДАНИЕ МНОГООКОННЫХ ПРИЛОЖЕНИЙ. MDI ПРИЛОЖЕНИЯ.

ЭЛЕМЕНТ УПРАВЛЕНИЯ NOTIFYICON

1. Диалоговые модальные SDI-окна

Новая форма добавляется в проект, как и любой другой элемент. В случае создания многооконного приложения, дочерних форм может быть несколько. Каждая форма может содержать свои ЭУ.

При создании формы события происходят в следующей последовательности:

конструктор – форма создается;

Load

– форма существует, но не отображена;

Activated

– форма становится видимой и текущей. (Идет се-

 

рия сообщений! Использовать не удалось.)

Исключение. Для Visible=true (Show c Visible=true):

• конструктор до Visible=true – форма создается, отображается и становится текущей;

Load

Activated

• конструктор после Visible=true – форма создается;

При закрытии формы события происходят в следующей последова-

тельности:

 

• Closing

– попытка закрыть форму

(CancelEventArgs e.Cancel=true – оставить форму открытой,

 

false – закрыть);

Closed

– после закрытия формы;

Deactivate

– после закрытия формы

Модальные диалоговые окна создаются методом ShowDialog(). Родительская форма блокируется до завершения работы с дочерней. Завершить работу дочерняя форма может либо закрыв себя методом

Close(), либо сделав себя невидимой (Visible=false). В последнем случае дочерняя форма остается открытой, но управление возвратится в родительскую форму, которая может выполнить Visible=true и опять сделать дочернюю форму видимой. Открытую дочернюю форму frm2 может закрыть родительская форма - frm2.Cancel().

private void Form1_Load(object sender, EventArgs e)

{

Visible = true; //принудительно высветить родительскую форму

Enabled = false; //погасить все поля

this.BackColor = System.Drawing.SystemColors.ControlDark;

Form2 dialog = new Form2(); dialog.ShowDialog();

Enabled = true;

this.BackColor = System.Drawing.SystemColors.Control;

. . .

380

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