Answer the question
In order to leave comments, you need to log in
How to update Winform data in DataGrid.DataSource table dynamically?
Hello.
After googling for a long time, I couldn't find a suitable answer.
The problem is the following:
There is a simple example of a table being poured into the DataGrid.DataSource
private List<Class1> Grep()
{
List<Class1> returns = new List<Class1>
{
new Class1{IdNum = _count},
new Class1{IdNum = _count},
new Class1{ IdNum = 1},
new Class1{ IdNum = 1},
new Class1{IdNum = 1},
new Class1{IdNum = 1},
new Class1{IdNum = 1},
};
return returns;
}
dataGridView1.DataSource = null;
dataGridView1.Refresh();
dataGridView1.Update();
private void btnClickStart_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = Grep();
for(int i = 0; i < 10; i++)
{
dataGridView1.DataSource = Grep();
_count++;
Thread.Sleep(300);
}
Answer the question
In order to leave comments, you need to log in
I found the answer myself. After 500 tries.
There are 2 options:
The most correct dynamic option is to change specific elements of the rows
dataGridView1[0,1].Value = "Some new value".
dataGridView1.Update();
dataGridView1.Refresh();
dataGridView1[0,1].Value = "Some new value".
dataGridView1.DataSource = Grep();
dataGridView1.Refresh();
dataGridView1.Update();
public class User : INotifyPropertyChanged
{
private string _name;
private int _age;
public string Name
{
get => _name;
set { _name = value; OnPropertyChanged(); }
}
public int Age
{
get => _age;
set { _age = value; OnPropertyChanged(); }
}
public User() { }
public User(string name, int age)
{
Name = name;
Age = age;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
var itemStates = new List<User>()
{
new User("Анимэшник", 0),
new User("Не анимэшник", 18)
};
var bindingList = new BindingList<User>(itemStates);
var source = new BindingSource(bindingList, null);
dataGridView1.DataSource = source;
await Task.Run(async () =>
{
for (int i = 18; i < 30; i++)
{
await Task.Delay(1000);
itemStates.Where(user => user.Name.Equals("Не анимэшник")).FirstOrDefault().Age = i;
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question