I have a dataGridView when I click on any row a form is opened to update the row data, but after ending updates the updating form is closed but the dataGridView data is not updated
How can i do that ?
I have a dataGridView when I click on any row a form is opened to update the row data, but after ending updates the updating form is closed but the dataGridView data is not updated
How can i do that ?
I know i am late to the party but hope this helps someone who will do the same with Class binding
var newEntry = new MyClassObject();
var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;
dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();
I know thats an old topic but i suddenly found the best way of doing it and it does not require nullifying the datasource and reassigning it. Just use a BindingList instead of a List.
for example:
//declare your list
private BindingList<myclass> mMyList = new BindingList<myclass>();
//then bind it to your datagrid, i usually do it on the Load event
private void Form1_Load(object sender, EventArgs e)
{
_dgMyDatagrig.DataSource = mMyList;
}
//start populating your list
private void addItem(mycclass item)
{
mMylist.add(item);
//the datagrid will show automatically the new added/updated items, no need to do anything else
}
You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():
private void RefreshGridView()
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke((MethodInvoker)delegate ()
{
RefreshGridView();
});
}
else
dataGridView1.Refresh();
}
I use the DataGridView's Invalidate() function. However, that will refresh the entire DataGridView. If you want to refresh a particular row, you use dgv.InvalidateRow(rowIndex). If you want to refresh a particular cell, you can use dgv.InvalidateCell(columnIndex, rowIndex). This is of course assuming you're using a binding source or data source.
I found this useful .NET documentation that demonstrates how to reset the bindings correctly, using BindingSource.ResetBindings.