How to display data in a grid in WinForms using C#?
In C#, WinForms can be used to display data in a grid format using the DataGridView control. Here is an example code:
- Add a DataGridView control to the form by either dragging and dropping it or dynamically adding it in the code.
- Bind data to the DataGridView control when the form is loaded.
// 假设数据源为一个List
List<Person> persons = new List<Person>();
persons.Add(new Person { Name = "Alice", Age = 25 });
persons.Add(new Person { Name = "Bob", Age = 30 });
// 绑定数据到DataGridView控件
dataGridView1.DataSource = persons;
- Custom data type Person:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
- Set properties of the DataGridView control, such as automatic column width adjustment, disallowing users to add rows, and disallowing users to edit.
By following the steps above, you can achieve grid-style data display in WinForms.