If you are using data binding to bind your values to the DataGridView
, instead of adding the row to the control itself you will have to add the new value to the actual list that the DataGridView
is bound to.
There is only one problem with that: Just adding the value to the data source will not refresh the DataGridView
so you will not see it in the UI.
So what you actually want to do is using a BindingSource
.
The BindingSource
is bound to the DataGridView.DataSource
and also has a DataSource
-Property itself wich is your actual list of values.
Here is a small example:
public partial class Form1 : Form
{
private BindingSource _dataSource;
public Form1()
{
InitializeComponent();
_dataSource = new BindingSource();
_dataSource.DataSource = new List<Person>
{
new Person { Name = "User1", Age = 1 },
new Person { Name = "User2", Age = 2 },
};
dataGridView1.DataSource = _dataSource;
}
private void button1_Click(object sender, EventArgs e)
{
_dataSource.Add(new Person { Name = "User3", Age = 3 });
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
(dataGridView1
was created by dragging-and-dropping it from the toolbox to the form so the properties all have default values)
I used this question as a reference for this answer:
How can I refresh c# dataGridView after update ?