在C# WinForms中,數(shù)據(jù)綁定可以通過以下步驟實(shí)現(xiàn):
首先,在窗體上添加一個控件,例如DataGridView。
創(chuàng)建一個數(shù)據(jù)源,例如List或DataTable。在這個例子中,我們創(chuàng)建一個List
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
}
List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "張三", Position = "經(jīng)理" },
new Employee { Id = 2, Name = "李四", Position = "助理" },
new Employee { Id = 3, Name = "王五", Position = "工程師" },
};
dataGridView1.DataSource = employees;
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn idColumn = new DataGridViewTextBoxColumn();
idColumn.DataPropertyName = "Id";
idColumn.HeaderText = "ID";
dataGridView1.Columns.Add(idColumn);
DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
nameColumn.DataPropertyName = "Name";
nameColumn.HeaderText = "姓名";
dataGridView1.Columns.Add(nameColumn);
DataGridViewTextBoxColumn positionColumn = new DataGridViewTextBoxColumn();
positionColumn.DataPropertyName = "Position";
positionColumn.HeaderText = "職位";
dataGridView1.Columns.Add(positionColumn);
現(xiàn)在,DataGridView應(yīng)該顯示數(shù)據(jù)源中的數(shù)據(jù)。如果需要更新數(shù)據(jù)源,可以直接修改List