How to bind data to a DataGridView control?
There are several ways to bind data to a DataGridView control:
- By using a BindingSource, you can create a BindingSource object, then bind a data source (such as a DataTable or List) to the BindingSource object, and finally bind the BindingSource object to a DataGridView control.
BindingSource bs = new BindingSource();
bs.DataSource = yourDataSource;
dataGridView.DataSource = bs;
- Directly binding data source: You can also directly bind the data source (such as DataTable, List, etc.) to the DataGridView control.
dataGridView.DataSource = yourDataSource;
- Manually add data: You can also add data to the DataGridView control line by line using code.
foreach (var item in yourDataSource)
{
dataGridView.Rows.Add(item.Property1, item.Property2, ...);
}
You can display and manipulate data in the DataGridView control using any method of data binding.