Home >Backend Development >C++ >How to Programmatically Add New Rows to a DataGridView?
Add new rows to DataGridView programmatically
When working with data using the DataGridView control, you may need to dynamically add new rows at runtime. Here's how to achieve this:
Use DataRows
<code class="language-c#">// 创建一个新的 DataTable 行 DataRow row = datatable1.NewRow(); // 设置列值 row["column2"] = "column2"; row["column6"] = "column6"; // 将新行添加到 DataTable datatable1.Rows.Add(row);</code>
Add to DataGridView
To add new rows to a DataGridView, there are several ways:
Method 1: Clone existing rows
<code class="language-c#">// 克隆现有行 DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone(); // 设置单元格值 row.Cells[0].Value = "XYZ"; row.Cells[1].Value = 50.2; // 将新行添加到 DataGridView yourDataGridView.Rows.Add(row);</code>
Method 2: Clone by column name
<code class="language-c#">// 克隆现有行 DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone(); // 按列名设置单元格值 row.Cells["Column2"].Value = "XYZ"; row.Cells["Column6"].Value = 50.2; // 将新行添加到 DataGridView yourDataGridView.Rows.Add(row);</code>
Method 3: Quickly insert multiple rows
<code class="language-c#">// 使用值插入多行 this.dataGridView1.Rows.Add("five", "six", "seven","eight"); // 在索引 0 处插入一行 this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");</code>
The above is the detailed content of How to Programmatically Add New Rows to a DataGridView?. For more information, please follow other related articles on the PHP Chinese website!