在 DataGridView 中添加按钮作为列

Add button as column in DataGridView

我目前正在开发一个 Winforms 项目,其中有一个 datagridview,我在该项目上显示了我的用户列表。我想在最后一列中添加一个按钮(除了基本参数都是 int 和 string 等),它将有一个 OnClick 侦听器。问题是,我没有数据源,我正在使用 BindingList 和 BindingSource 对象;我试图向网格中显示的 class 添加一个按钮变量,但没有成功;我找不到将 Button 转换为 DataGridViewCell 的方法。如何在每一行的末尾添加一个按钮?

代码:

var bindingList = new BindingList<userDisplay>(usersListDGV); //userDisplay has int and string variables
var source = new BindingSource(bindingList, null);
usersDGV.DataSource = source;

我建议您将网格设置为 AutoGenerateColumns = false,然后为绑定源中的每个字段添加一列,并适当设置 DataPropertyName 以便绑定该列。您可以通过 UI 或在代码中执行此操作。然后添加一个 DataGridViewButtonColumn 并处理 CellClickEditingControlShowing 事件以连接点击处理程序,如前所述 here.