DataTable datatable = new DataTable();
// Add columns to datatable
datatable.Columns.Add("No.");
datatable.Columns.Add("First name");
datatable.Columns.Add("Last name");
// Add rows to datatable
foreach (var row in EmployeeContext.Employees) //EmployeeContext.Employees is a static list
{
datatable.Rows.Add(row.No, row.FirstName, row.LastName);
}
//Clear datagridview
dataGridView1.DataSource = null;
dataGridView1.Refresh();
//Add 'column name' and 'header texts' to datagridview
dataGridView1.Columns.Add("No", "No.");
dataGridView1.Columns.Add("FirstName", "First name");
dataGridView1.Columns.Add("LastName", "Last name");
//Add 'button' dynamically to datagridview
DataGridViewButtonColumn deleteButton = new DataGridViewButtonColumn();
deleteButton.FlatStyle = FlatStyle.Popup;
deleteButton.Text = "Delete";
deleteButton.HeaderText = "Delete";
dataGridView1.Columns.Add(deleteButton);
//Define datapropertyname using 'column name' property defined in previous step
dataGridView1.Columns["No"].DataPropertyName = "No.";
dataGridView1.Columns["FirstName"].DataPropertyName = "First name";
dataGridView1.Columns["LastName"].DataPropertyName = "Last name";
dataGridView1.DataSource = datatable;
问题1:可以看到第4行的按钮,但索引显示为' 0'而不是三个
问题2:添加按钮上的额外按钮列单击