Как добавить строку в datagridview

от admin

Add a Row in DataGridView Using C#

In this article, we’ll learn about DataGridView in C#. Let’s first take some idea about DataGridView and why we need to store data in the table, i.e., in rows and columns.

Please enable JavaScript

Next, we will discuss various ways to add rows to the grid.

In the past, most developers stored their data in files. Whenever they needed it, they had to search through all the files sequentially, which was time-consuming.

The tables were invented to overcome this problem.

In the table, data is stored in rows and columns sequentially in a well-organized manner. Tables provide fast and efficient readability across rows and columns without being time-consuming.

Grid is also the form of the table in the form of cells, i.e., rows and columns.

DataGridView in C#

Visual Studio 2008 has the DataGridView control available in Windows Forms controls. This control has added extensive power to manage data compared to previous versions.

Besides strength, this control provides flexibility to display data in the row-column form.

We can use the DataGridView control to show read-only views for a small amount of data. You can also use it for large data sets to show editable views.

Besides small and large data sets, you can also display master details using this control.

The DataGridView control is available for a variety of different data sources for the view as well as for editing. This control has a simple and intuitive way of binding data to this control.

To bind multiple tables in a data source, set it as a string in the property of DataMember .

  1. IList interface also includes one-dimensional arrays.
  2. IListSource interface. The examples are the DataSet classes and DataTable .
  3. IBindingList interface, like BindingList<(Of <(T>)>) class.
  4. IBindingListView interface, like the BindingSource class.

The DataGridView control can bind data to the public attributes of the objects described by the above interfaces. The DataGridView control mainly attaches a BindingSource , whereas the BindingSource is bound to another reference data source or with the business object.

This control also supports data binding to the properties collection returned by an ICustomTypeDescriptor interface.

The DataGridView in C# displays data in a customizable grid, i.e., in tabular form with Windows Form. It is part of the System.Windows.Forms namespace.

The syntax of using a grid is given below.

You can customize the cells, rows, columns, and borders through the DataGridView class. The DataGridView control displays data with or without a data source.

If you still need to provide a Data source, you can add rows and columns in DataGridView by rows and columns properties. You can also access rows and column collections using DataGridView rows and cols objects.

In this article, our primary focus is adding rows in the data grid view, so let’s find some methods.

Add Rows in DataGridView in C#

We will discuss multiple ways to add rows in DataGridView . We will present coding details with each method.

Manual Addition of Rows

The easiest way to add rows in DataGridView can be done manually using the Rows.Add() method in the data grid view. In the following example, in the MyForm.cs class, the add_Data button function is written, which will display rows.

You can create a form design in WPF FormDesign using a grid and a button that displays the grid.

You can also access the DataGridView control’s columns using the Columns collection and the DataGridView control’s rows using the Rows collection.

If DataGridView is not bound to any data table or data set, we can add new rows with the help of the following code.

Adding a New Row Dynamically

The following example shows how you can dynamically add columns and rows in the grid in the Windows application form Form1 . After creating the project, add the dataGridView from the toolbox to your Form1.cs[Design] and click on the dock for the container option from the top right button of the grid.

Now go to the Form1.cs file and do some changes to the Form. First, add the namespaces, as given below.

In the above code, you can see that initialize the form component and then create a Form1_Load_1 function to handle objects and events that occurred on the grid and pass the updateGrid() where to add columns and rows. Rows in the grid have been added to the ArrayList object as it can store objects in the group and can manipulate them.

The output of the above code is given below.

Adding Rows in Grid Through the Data Table

In the C# WinForm, multiple ways exist to add data to the grid. Simply put, the data table can be defined as an object mainly used in databases.

It is like a database table having rows and columns. If you want to read more about the data table, you can visit the article by Microsoft.

In the below example, you can see that first, we created the data table object and added columns and rows in the grid using the built-in properties of the data table. The data source is also the property of the data table, mainly used to get or set the data for the DataGridView .

When the Add_Row is pressed after filling data in textboxes, the data source will populate the data to the grid.

The output of the above code is:

Adding Rows Through Clone Method

In C#, you can add rows in the grid using the clone method. Clone means copying the data from one DataGridView to another for adding rows and columns in a grid.

Although its primary purpose is to copy the data from one grid to another, you can add rows. For example:

The above code represents the one-row value to be added to the grid. However, you can also create a row template, as it provides better arrangements of rows in a cell.

Although there are different methods to add rows in the data grid view dynamically, here are a few examples:

We have just used the above code for this example as it is easy to understand. In DataGridView , the clone property is used to copy the rows and their properties and populate the row copy with the original one.

In the above code, we have used the clone method to copy the rows. To read more about the clone method, you can visit this page.

The output of the above code is:

You can visit this page to read about adding rows in the data grid view. If you still have ambiguity in adding rows in the grid, you can also read this article.

We have discussed DataGridView in detail. We have discussed multiple ways to bind data to DataGridView .

We hope you have a good idea about the data grid view and its functionalities and that you are comfortable adding rows through different grid methods and setting its property.

Читать:
Как проверить обновление драйверов на виндовс 11

Как добавить строку в DataGridView в языке c#

Из этой статьи Вы узнаете, как добавить строку в DataGridView.

И так, как обычно для начала создадим простое Windows Forms приложение на языке c#, после чего добавим на форму: DataGridView (dgv), кнопку и textBox.

28469

Чтобы добавить новую строку в DataGridView нужно воспользоваться методом Add, например:

Первый параметр &#8212; это имя колонки, а второй &#8212; это
название колонки, которое будет отображаться в DataGridView.

Снова попробуем добавить строку в DataGridView.

Либо можно сразу же передать значения в качестве параметров, например:
dgv.Rows.Add(0, textBox1.Text);
результат

28470

Теперь всё в порядке задача решена.

Здесь стоит обратить внимание на один важный момент. По умолчанию в DataGridView рядом с пунктом Enable Adding включена галочка, которая даёт возможность пользователям вручную добавлять строки прямо в самом элементе DataGridView.

28471

Но также её включение приводит к тому, что каждый раз, перед
выполнением метода Add, в коллекцию строк будет автоматически
добавляться новая строка.

28472

Поэтому в данном примере мы можем вообще не вызывать метод Add, а
сразу же заполнить ячейки уже существующей строки нужными нам
значениями, например:

How to add a new row to datagridview programmatically

Habib's user avatar

Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows.

Here’s how you do it.

Or you need to set there values individually use the propery .Rows() , like this:

Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).

Create a clone row from RowTemplate is safer imho:

This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)

According to docs: «CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template».

If the grid is bound against a DataSet / table its better to use a BindingSource like

here is another way to do such

RC-AI's user avatar

If you need to manipulate anything aside from the Cell Value string such as adding a Tag, try this:

If you are binding a List

If you are binding DataTable

Mohammad Hasan Salmanian's user avatar

you can also create a new row and then add it to the DataGridView like this:

If anyone wanted to Add DataTable as a source of gridview then—

AbdusSalam's user avatar

An example of copy row from dataGridView and added a new row in The same dataGridView:

Sherif Hamdy's user avatar

Consider a Windows Application and using Button Click Event put this code in it.

Rei Salazar's user avatar

If you´ve already defined a DataSource , You can get the DataGridView ´s DataSource and cast it as a Datatable .

Элемент управления dataGridView

В Microsoft Visual Studio элемент управления dataGridView разработан для использования в приложениях, созданных по шаблону Windows Forms Application . Данный элемент управления позволяет организовывать данные в виде таблицы. Данные могут быть получены из базы данных, коллекции, внутренних переменных — массивов или других объектов программы.

Данный элемент управления аналогичен компоненту TStringGrid в системе визуальной разработки приложений.

Данный элемент размещен на панели инструментов ToolBox во вкладках «All Windows Forms» или «Data» (рисунок 1).

После размещения на форме, система создает объект (переменную) с именем dataGridView1 . С помощью этого имени можно программно оперировать методами и свойствами этого элемента управления.

C# элемент управления dataGridView свойства

Рис. 1. Элемент управления dataGridView1 и окно Properties со свойствами

2. Можно ли использовать DataGridView непосредственно без связывания его с базой данных?

Да, можно. В DataGridView данные могут быть получены из базы данных, коллекции, внутренних структур данных (массивов, структур и т.д.).

3. Как программно задать размеры DataGridView ? Свойства Width , Height

Для задания размеров DataGridView используются свойства Width и Height .

4. Какие виды данных могут быть представлены в ячейках DataGridView ?

Виды данных, которые могут быть представлены в ячейках dataGridView :

  • dataGridViewButtonColumn . Ячейки представлены в виде кнопок типа Button ;
  • dataGridViewCheckBoxColumn . Ячейки представлены элементами управления типа CheckBox , которые позволяют выбирать несколько вариантов (опций) из набора предложенных;
  • dataGridViewComboBoxColumn . Ячейки представлены элементами управления типа ComboBox , предназначенных для выбора одного из нескольких вариантов;
  • dataGridViewImageColumn . Ячейки таблицы есть изображениями типа Image;
  • dataGridViewLinkColumn . Ячейки таблицы представлены ссылками;
  • dataGridViewTextBoxColumn . Этот вариант предлагается по умолчанию при добавлении (создании) нового столбца. В этом случае ячейки таблицы представлены в виде полей ввода. Это позволяет вводить данные в таблицу как в матрицу.
5. Добавление столбца программным путем

Добавить столбец в dataGridView можно:

  • с помощью специального мастера;
  • программным путем.

Столбцы в dataGridView организованы в виде коллекции Columns типа DataGridViewColumnCollection. Чтобы добавить столбец программным путем используется метод (команда) Add из коллекции Columns.

Метод Add имеет 2 варианта реализации:

  • DataGridViewColumn – тип System.Windows.Forms.Column который добавляется;
  • ColumnName – название, по которому будет осуществляться обращение к столбцу из других методов;
  • HeaderText – текст, который будет отображаться в заголовке столбца.

Фрагмент кода, который добавляет два произвольных столбца следующий:

В реальных программах название столбца и его заголовка получаются из других элементов управления, например TextBox .

Для вставки столбца используется метод Insert , который имеет следующее объявление

Вызов этого метода из программного кода аналогичен методу Add .

6. Как программно реализовать удаление столбца? Методы Remove() и RemoveAt()

Чтобы удалить столбец используется один из двух методов из коллекции Columns :

  • метод RemoveAt() – удаляет столбец по заданному индексу в коллекции;
  • метод Remove() – удаляет столбец по его имени.

Общий вид метода RemoveAt() :

  • index – заданный индекс в коллекции. Индексы нумеруются с 0.
  • ColumnName – название столбца (но не название заголовка столбца), которое задается в методе Add() первым параметром. Столбцы в коллекции могут иметь одинаковые значения ColumnName . Если при вызове метода Remove() , столбца с именем ColumnName нет, то генерируется исключительная ситуация.

Фрагмент кода удаления столбца с помощью метода RemoveAt() :

7. Программное добавление строки. Метод Add()

Добавлять строку можно одним из двух способов:

  • путем непосредственного ввода с клавиатуры;
  • программным путем.

Строки в DataGridView организованы в виде коллекции Rows типа dataGridViewRowCollection .

Ниже приведен фрагмент метода, добавляющего 2 произвольные строки в таблицу

8. Программное удаление строки. Методы Remove() и RemoveAt()

Для удаления строки используется один из двух методов:

  • метод RemoveAt() – удаляет строку по заданному индексу;
  • метод Remove() – удаляет строку, которая есть входным параметром типа DataGridViewRow.

Фрагмент кода удаления строки имеет вид:

9. Задание текста заголовка в заданном столбце программным путем

Чтобы задать текст заголовка в заданном столбце используется свойство HeaderText . Фрагмент кода установки текста заголовка в столбце с индексом 0 имеет вид:

10. Установка выравнивания заголовка в заданном столбце программным путем

Выравнивание заголовка в столбце задается с помощью свойства HeaderCell.Style.Alignment .

Фрагмент кода установки выравнивания в заголовке столбца с индексом 0:

11. Установка шрифта заголовка в столбцах программным путем

Для установки шрифта в заголовках столбцов используется свойство ColumnHeadersDefaultCellStyle . В этом свойстве используется свойство Font .

Во фрагменте кода создается шрифт Arial , имеющий размер 12 и курсивное начертание.

12. Установка цвета шрифта заголовков программным путем

Чтобы задать цвет шрифта заголовков программным путем нужно использовать свойство ColumnHeaderDefaultCellStyle . В этом свойстве есть свойства ForeColor и BackColor .

Похожие статьи