ispiro
ispiro

Reputation: 27633

DataGridView with Data Binding - new Row not showing

I have a DataGridView bound to List of a Class1 as in my previous question (By the way - the answer there was to use properties instead of fields) . I'm then adding a row with the following code:

l.Add(new Class1 { a = 5, b = 6 });

I checked and the Row is added to the List. But the DataGridView is not being updated. How is that fixed?

Upvotes: 2

Views: 6682

Answers (5)

Gurpreet
Gurpreet

Reputation: 1

you can use BindingSource, here I have example with Datatable, when any thing get changed in datasource it will reflected at the same time without any refresh function. If want to add new row, just need to update datatable.

private BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dt;
//datagridview column binding
ID.DataPropertyName = "ID";
Name.DataPropertyName = "Name";
grdCharges.DataSource = bindingSource;

Upvotes: 0

tom2051
tom2051

Reputation: 80

The property AllowUserToAddRows of the DataGridView must be true.

The DataSource for the DataGridView must be a BindingSource. Its property AllowNew must be true.

You can create a BindingSource (here named personBindingSource) for the DGV in the Designer by editing its property DataSource... The DataSource of the BindingSource might be a List<Person>.

So this works fine...

// personBindingSource was already created in the Designer ...
personBindingSource.DataSource = null;
personBindingSource.DataSource = _lstPerson;

dgvPerson.DataSource = personBindingSource;
dgvPerson.Refresh();

The new line will be shown :-)

This does not work...

dgvPerson.DataSource = _lstPerson;
dgvPerson.Refresh();

the DGV still contains all elements but in this case the new line will not be shown :-(

Maybe this helps ...

Upvotes: 2

ispiro
ispiro

Reputation: 27633

An answer to another question of mine solved this one as well. Use a BindingSource as an intermediate, and use:

bindingSource.Add(new Class1 { a = 5, b = 6 });

Upvotes: 1

Kunal Khatri
Kunal Khatri

Reputation: 471

you should set it following way. after you add new item in the list, you must set Datasource null, and reassign it to dataGridview.

    List<Person> lst = new List<Person>();
    private void button5_Click(object sender, EventArgs e)
    {

        lst.Add(new Person("X"));
        lst.Add(new Person("y"));

        dataGridView2.DataSource = lst;

        lst.Add(new Person("Z"));

        dataGridView2.DataSource = null;
        dataGridView2.DataSource = lst;
    }

 public class Person
    {
        public Person(string fname)
        {
            this.firstname = fname;
        }
        public string firstname { get; set; }
    }

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29006

You have to re-Assign the Datasource, in case of any changes made in the bounded source, or that are in two way bounded:

grid.DataSource = null;
grid.DataSource = l;

Upvotes: 2

Related Questions