How to bind data source to datagridview in C#?
The steps to bind a data source to a DataGridView in C# are as follows:
- Drag and drop a DataGridView control onto the form, and configure the properties and styles of the columns.
- Create a data source in the code, which can be a DataTable, a List collection, or another data type that supports binding.
- You can use the following code to bind the data source to the DataGridView control in the form load event.
// 创建数据源(示例为DataTable)
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// 添加数据到数据源
table.Rows.Add(1, "John");
table.Rows.Add(2, "Mary");
table.Rows.Add(3, "Tom");
// 将数据源绑定到DataGridView控件
dataGridView1.DataSource = table;
- To set the auto-generate column mode for the DataGridView control (if needed), you can use the following code:
dataGridView1.AutoGenerateColumns = true;
- When the program runs, the data from the data source will be displayed in the DataGridView control.
Before binding the data source, it is important to make sure that the columns of the DataGridView control are correctly set up, otherwise the data may not be displayed correctly. If you need to change the way columns are displayed, you can modify the relevant properties of the DataGridView control in the code.