C DataGridView 2 methods to add a new row

  • 2020-05-09 19:09:53
  • OfStack

You can statically bind the data source, which automatically adds the corresponding row to the DataGridView control. If you need to dynamically add new lines to an DataGridView control, there are many ways to do this. Here are two ways to dynamically add new lines to an DataGridView control:


Method 1:


int index=this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[0].Value = "1"; 
this.dataGridView1.Rows[index].Cells[1].Value = "2"; 
this.dataGridView1.Rows[index].Cells[2].Value = " Listening to the ";

Add a new row to the DataGridView control with the dataGridView1.Rows.Add () event, which returns the index number of the new row added, that is, the line number of the new row, through which you can then manipulate the individual cells of the row, such as dataGridView1.Rows [index].Cells[0].Value = "1". This is a very common and simple method.


Method 2:


DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell();
textboxcell.Value = "aaa";
row.Cells.Add(textboxcell);
DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell();
row.Cells.Add(comboxcell);
dataGridView1.Rows.Add(row);

Method 2 is a little more complex than method 1, but it is useful in special situations, such as when you want to add controls such as drop-down boxes, buttons, and so on to certain cells in a new line.
DataGridViewRow row = new DataGridViewRow(); Is the row object that creates DataGridView, DataGridViewTextBoxCell is the content of the cell TextBox, DataGridViewComboBoxCell is the content of the cell TextBox, DataGridViewComboBoxCell is the content of the cell TextBox, DataGridViewButtonCell is the content of the cell DataGridViewButtonCell is the button, and so on. textboxcell is an object for a newly created cell, and you can add its properties to that object. Then add the textboxcell cell to the row object via row.Cells.Add (textboxcell). To add other cells, do the same.
Finally, a new line row is added to the dataGridView1 control via dataGridView1.Rows.Add (row).


Related articles: