C#. Windows Forms. Demonstration of the operation of the dataGridView control




Demonstration of the operation of the dataGridView control

In Microsoft Visual Studio, the DataGridView control is designed for use in applications created using the Windows Forms Application template. This control allows you to organize data in the form of a table. Data can be obtained from a database, a collection, internal variables – arrays or other program objects.

This topic demonstrates the use of the DataGridView element to implement a two-dimensional table (matrix) whose cells can be edited. Each table cell is represented by a separate TextBox control. As you know, in Microsoft Visual Studio implemented a TextBox control, which allows the user to enter text that provides multi-line editing, text input by mask.


Contents


Search other websites:

Instructions

1. Run Microsoft Visual Studio

 

2. Create an application using the Windows Forms Application template

To create a new application, you need to call the command

File->New->Project...

As a result, the “New Project” window opens. In the left part of the window, in the “Recent Templates” tab, you must specify “Visual C#”. In the right part of the window, select the Windows Forms Application template.

A more detailed example of creating an application using the Windows Forms Application template is described in the topic:

For a newly created project, you specify the folder (the Location field) and the project name (by default WindowsFormsApplication1. The folder can be arbitrary, for example

C:\Programs\C_Sharp

After selecting OK in the New Project window, the form of application and the corresponding project files will be created. The form name remains Form1.

 

3. Designing the form of application

3.1. Placement of the DataGridView control on the form

Place a DataGridView control on the form (Figure 1). This control can be found on the ToolBox toolbar in the “All Windows Forms” or “Data” tabs.

After placement, the system creates an object (variable) named dataGridView1. Using this name, you can programmatically manipulate the methods and properties of this control.

C#. Windows Forms. The DataGridView1 control and Properties window

Figure 1. The DataGridView1 control and Properties window

 

3.2. Setting the size and shape dataGridView1 control. The Size property

In order to correctly display, it is needed to configure the sizes and shapes of Form1 form and dataGridView1 control.

Dimensions are set approximately as shown in Figure 2. Dimensions can be configured programmatically or manually with the mouse. To customize the dimensions of dataGridView1 using the Properties window, you need to use the Size property (Figure 2).

C#. Windows Forms Application template. The Size property of the dataGridView1 control

Figure 2. The Size property of the dataGridView1 control

To set the size of dataGridView1 programmatically, you can use, for example, the following code

// set the size of dataGridView1
// Height - 200 pixels. Width - 350 pixels
dataGridView1.Width = 350;
dataGridView1.Height = 200;

 

3.3. Placing and configuring the Button and Label controls on the form

Place the 17 controls of Button type on the form (Figure 3). Automatically 17 objects (variables) with the names button1, button2, …, button17 are created.

C#. Windows Forms Application template. Placement of Button controls

Figure. 3. Placement of Button controls

Customize the ‘Text’ properties of the placed buttons:

  • in the button1 control, property Text = “Add Column”;
  • in the button2 control, property Text = “Delete Column”;
  • in the button3 control, property Text = “Add row”;
  • in the button4 control, property Text = “Delete row”;
  • in the button5 control, property Text = “Title text”;
  • in the button6 control, property Text = “Title alignment”;
  • in the button7, property Text = “Font of title”;
  • in the button8, property Text = “Header font color”;
  • in the button9, property Text = “Set the size of dataGridView1”;
  • in the button10, property Text = “Width of the first column”;
  • in the button11, property Text = “Row Height”;
  • in the button12, property Text = “Alignment in a column”;
  • in the button13, property Text = “Font in the first column”;
  • in the button14, property Text = “Number of columns”;
  • in the button15, property Text = “Number of rows”;
  • in the button16, property Text = “Column Width”;
  • in the button17, property Text = “Row Height”.

In all controls, set the AutoSize property to true.

To display information, you also need to place a control on the form of the Label type. After placement, the form of the application takes the form, as shown in Figure 4.

C#. Windows Forms. The form of application after placement and configuration of controls

Figure 4. The form of application after placement and configuration of controls

 

4. Programming event handlers for dataGridView1 operation control

To run the program, you need to program the click events on the buttons button1, button2, …, button17. A detailed example of programming the Click event of a Button control is described in the topic:



 

4.1. The Add Column command

Types of data that can be represented in DataGridView cells:

  • dataGridViewButtonColumn. Cells are represented as buttons of type Button;
  • dataGridViewCheckBoxColumn. The cells are represented by CheckBox controls, which allow you to select several options (options) from the set of proposed ones;
  • dataGridViewComboBoxColumn. The cells are represented by the ComboBox type control elements, designed to select one of several options;
  • dataGridViewImageColumn. Table cells are images of type Image;
  • dataGridViewLinkColumn. Table cells are represented by references;
  • dataGridViewTextBoxColumn. This option is proposed by default when adding (creating) a new column. In this case, the table cells are represented as input fields. This allows you to enter data into a table as a matrix.

You can add a column in the dataGridView in two ways:

  • with the help of a special master;
  • programmatically.

 

4.1.1. Adding a column using the special Microsoft Visual Studio Wizard

To add a column in the DataGridView using the wizard, you need to do the following:

  • call the menu “DataGridView Tasks” (Figure 5) by clicking on the right arrow (right upper part of the rectangular area dataGridView1);
  • in the “DataGridView Tasks” menu, select the “Add Column …” command. This will open the “Add Column” window, where you can customize the column name, column data type, title, and so on.

C#. Windows Forms. DataGridView control. Task selection window "DataGridView Tasks"

Figure 5. Task selection window “DataGridView Tasks”

C#. Windows Forms. Control DataGridView. Adding a column using the wizard

Figure 6. Adding a column using the wizard

 

4.1.2. Adding a column programmatically

Columns in the DataGridView are organized as a Columns collection of the DataGridViewColumnCollection type. To add a column programmatically, use the Add method (command) from the Columns collection.

The Add method has 2 implementation options:

int DataGridViewColumnCollection.Add(DataGridViewColumn dataGridViewColumn);

int DataGridViewColumnCollection.Add(string ColumnName, string HeaderText);

where

  • DataGridViewColumn – type System.Windows.Forms.Column that is added;
  • ColumnName – the name by which the column will be referenced from other methods;
  • HeaderText – text that will be displayed in the header of the column.

The text of the event handler for adding two arbitrary columns is as follows:

private void button1_Click(object sender, EventArgs e)
{
    // Add a column named column-1, the header of the column is "Header column-1"
    dataGridView1.Columns.Add("column-1", "Header column - 1");

    // Add a column named 'column-2'
    dataGridView1.Columns.Add("column-2", "Header column - 2");

    label1.Text = "Columns added";
}

In real programs, the name of the column and its header are obtained from other controls, for example, TextBox.

To insert a column, use the Insert method, which has the following declaration

void DataGridViewColumnCollection.Insert(int columnIndex, DataGridViewColumn dataGridViewColumn);

Calling this method from the program code is similar to the Add method.

 

4.2. The “Delete Column” command

To delete a column, use one of two methods from the Columns collection:

  • the RemoveAt() method – removes the column at the specified index in the collection;
  • the Remove() method removes the column by its name.

General view of the RemoveAt() method:

void DataGridViewColumnCollection.RemoveAt(int index);

where

  • index – the specified index in the collection. Indexes are numbered from 0.
void DataGridViewColumnCollection.Remove(string ColumnName);

where

  • ColumnName – the name of the column (but not the title of the column header) that is specified in the Add() method by the first parameter. Columns in a collection can have the same ColumnName value. If the call to the Remove() method does not have a column named ColumnName, an exception is thrown.

The program code for deleting a column using the RemoveAt() method:

private void button2_Click(object sender, EventArgs e)
{
    // deleting a column at index
    int index; // number of the column to be deleted
    int n; // the current number of columns in the dataGridView

    // set column number to be deleted
    index = 1;

    // determine the current number of columns in the dataGridView
    n = dataGridView1.Columns.Count;

    // deleting
    if ((n > 0) && (index >= 0) && (index < n))
    {
        dataGridView1.Columns.RemoveAt(index);
        label1.Text = "Column deleted";
    }
    else
    {
        label1.Text = "Column not deleted";
    }
}

 

4.3. The “Add row” command

You can add a row in one of two ways:

  • by direct input from the keyboard;
  • programmatically.

The rows in the DataGridView are organized as a collection of Rows, such as dataGridViewRowCollection. Below is an event handler that adds 2 arbitrary rows to the table

private void button3_Click(object sender, EventArgs e)
{
    // Add rows to the table
    if (dataGridView1.Columns.Count <= 0)
    {
        label1.Text = "Rows are not added";
        return;
    }

    dataGridView1.Rows.Add("Ivanov I.I.", 25, "New York");
    dataGridView1.Rows.Add("Petrenko P.P.", 38, "Moscow");
    label1.Text = "Rows are added";
}

 

4.4. The “Delete row” command

To delete a row, use one of two methods:

  • method RemoveAt() – deletes the string at the specified index;
  • the Remove() method removes a string that is an input parameter of the DataGridViewRow type.

The event handler for the row deletion looks like this:

private void button4_Click(object sender, EventArgs e)
{
    // Delete row
    int nr, nc;
    nc = dataGridView1.Columns.Count; // number of columns
    nr = dataGridView1.RowCount;

    if ((nc > 0) && (nr > 1))
    {
        dataGridView1.Rows.RemoveAt(0); // delete the first row
        label1.Text = "Row is deleted";
    }
    else
    {
        label1.Text = "Row is not deleted";
    }
}

 

4.5. Working with the header of the specified column
4.5.1. Set the header text in the specified column programmatically

To set the header text in the specified column, use the HeaderText property. The text of the header text event handler in the column with the index 0 is:

private void button5_Click(object sender, EventArgs e)
{
    // set text in title
    int nc = dataGridView1.ColumnCount;

    if (nc > 0)
    {
        // set new text in the header of the first column
        dataGridView1.Columns[0].HeaderText = "Header - 1";
        label1.Text = "Text is set";
    }
    else
    {
        label1.Text = "Text is not set";
    }
}

 

4.5.2. Set the header alignment in the specified column programmatically

The alignment of the header in the column is specified using the HeaderCell.Style.Alignment property.

The program code for the alignment setup event handler in the column header with the index 0:

private void button6_Click(object sender, EventArgs e)
{
    // title alignment
    int nc;
    nc = dataGridView1.ColumnCount;

    if (nc > 0)
    {
        // Set the alignment in the center (horizontally and vertically)
        dataGridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        label1.Text = "Alignment complete";
    }
    else
    {
        label1.Text = "Alignment not performed";
    }
}

 

4.5.3. Specify the title font in the columns programmatically

To set the font in the column headers, use the ColumnHeadersDefaultCellStyle property. This property uses the Font property.

In the event handler, the Arial font is created, having a size of 12 and italic font.

private void button7_Click(object sender, EventArgs e)
{
    // set the font of the title
    int nc;
    nc = dataGridView1.ColumnCount;

    // create a font "Arial", size 12, font - "italics"
    Font F = new Font("Arial", 12, FontStyle.Italic);

    if (nc > 0)
    {
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = F;
        label1.Text = "Font is set";
    }
    else
    {
        label1.Text = "The font is not set";
    }
}

 

4.5.4. Set the font color of headings programmatically

To set the font color of the headers programmatically, you must use the ColumnHeaderDefaultCellStyle property. This property has ForeColor and BackColor properties.

private void button8_Click(object sender, EventArgs e)
{
    int nc;
    nc = dataGridView1.ColumnCount;

    if (nc > 0)
    {
        // create a system font
        Font F = new Font("Arial", 14);

        // set the color in column headers
        dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.Purple;

        // set the font
        dataGridView1.Columns[0].DefaultCellStyle.Font = F;

        label1.Text = "Header color is changed";
    }
    else
    {
        label1.Text = "Color not changed";
    }
}

 

4.6. Working with the parameters of columns, rows, cells
4.6.1. Setting the size of dataGridView1 programmatically
private void button9_Click(object sender, EventArgs e)
{
    // set the size of dataGridView1
    dataGridView1.Width = 600;
    dataGridView1.Height = 150;
    label1.Text = "Size is set";
}

 

4.6.2. Set the width of the specified column dataGridView1
private void button10_Click(object sender, EventArgs e)
{
    // set the width of a column
    int nc;
    nc = dataGridView1.ColumnCount;

    if (nc > 0)
    {
        dataGridView1.Columns[0].Width = 70;
        label1.Text = "Column width is set";
    }
    else
    {
        label1.Text = "Column width is not set";
    }
}

 

4.6.3. Setting the height of the specified row dataGridView1
private void button11_Click(object sender, EventArgs e)
{
    // set the height of row
    int nc, nr;
    nc = dataGridView1.ColumnCount;
    nr = dataGridView1.RowCount;

    if ((nc > 0) && (nr > 1))
    {
        dataGridView1.Rows[0].Height = 50;
        label1.Text = "Row height is set";
    }
    else
    {
        label1.Text = "Row height is not set";
    }
}

 

4.6.4. Setting the alignment in the specified column and row
private void button12_Click(object sender, EventArgs e)
{
    // alignment in the rows
    int nc, nr;
    nc = dataGridView1.ColumnCount;
    nr = dataGridView1.RowCount;

    if ((nc > 0)&&(nr>1))
    {
        // alignment for all rows
        dataGridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;

        // alignment for a row with index 0
        dataGridView1.Rows[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

        // alignment for a column with index 0
        dataGridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomLeft;
    }
}

 

4.6.5. Setting the font, color of characters and background in the first column

To set the font, color of characters and background in the first column, the DefaultCellStyle property of the column with index 0 is used. This property has the properties Font, BackColor, ForeColor.

Below is an event handler that sets the color of the font, characters, and background in the dataGridView1.

private void button13_Click(object sender, EventArgs e)
{
    // font and color in the first column
    int nc, nr;
    nc = dataGridView1.ColumnCount;
    nr = dataGridView1.RowCount;

    if ((nc > 0) && (nr > 1))
    {
        // create a font
        Font F = new Font("Times New Roman", 10, FontStyle.Bold);

        // color of symbols and background in the first column
        dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Red;
        dataGridView1.Columns[0].DefaultCellStyle.ForeColor = Color.Blue;

        // font in the first column
        dataGridView1.Columns[0].DefaultCellStyle.Font = F;

        label1.Text = "Font and color in the 1st column are changed";
    }
    else
    {
        label1.Text = "Font and color in the 1st column are not changed";
    }
}

 

4.7. Getting information about columns and rows dataGridView1
4.7.1. Determine the number of columns
private void button14_Click(object sender, EventArgs e)
{
    // Determine the number of columns
    int n;
    n = dataGridView1.Columns.Count;
    label1.Text = n.ToString();
}

 

4.7.2. Determine the number of rows
private void button15_Click(object sender, EventArgs e)
{
    // Determine the number of rows without the title row
    int n;
    n = dataGridView1.Rows.Count;
    label1.Text = (n - 1).ToString();
}

 

4.7.3. Determine the width of the specified column in pixels
private void button16_Click(object sender, EventArgs e)
{
    // column width in pixels
    int w;
    int nc;
    nc = dataGridView1.Columns.Count;

    if (nc > 0)
    {
        w = dataGridView1.Columns[0].Width;
        label1.Text = w.ToString();
    }
}

 

4.7.4. Determine the height of the specified row in pixels
private void button17_Click(object sender, EventArgs e)
{
    // Determine the height of the specified row in pixels
    int h;
    int nr, nc;
    nc = dataGridView1.Columns.Count;
    nr = dataGridView1.RowCount;

    if ((nr>1)&&(nc>0))
    {
        h = dataGridView1.Rows[0].Height;
        label1.Text = h.ToString();
    }
}

 

5. Run the program

 


Related topics