在C# WinForms中,數據綁定可以通過以下步驟實現:
首先,在窗體上添加一個控件,例如DataGridView。
創建一個數據源,例如List或DataTable。在這個例子中,我們創建一個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 = "經理" },
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);
現在,DataGridView應該顯示數據源中的數據。如果需要更新數據源,可以直接修改List