我将DataGridView控件绑定到List集合。所以,我可以编辑集合的元素。有没有办法使用此网格启用删除和添加元素?
答案 0 :(得分:4)
通用List<T>
并不完全支持与DataGridView
的绑定,因为您可以看到您可以编辑列表中的项目但不能添加或删除。
您需要使用的是BindingList<T>
或BindingSource
。
BindingList<T>
将允许您使用UI在网格中添加和删除行 - 当您将DataSource
更改为此时,您将在网格的底部看到空白的新行。您仍然无法以编程方式添加或删除行。为此,您需要BindingSource
。
以下两个示例(使用示例Users类,但其详细信息在此处并不重要)。
public partial class Form1 : Form
{
private List<User> usersList;
private BindingSource source;
public Form1()
{
InitializeComponent();
usersList = new List<User>();
usersList.Add(new User { PhoneID = 1, Name = "Fred" });
usersList.Add(new User { PhoneID = 2, Name = "Tom" });
// You can construct your BindingList<User> from the List<User>
BindingList<User> users = new BindingList<User>(usersList);
// This line binds to the BindingList<User>
dataGridView1.DataSource = users;
// We now create the BindingSource
source = new BindingSource();
// And assign the List<User> as its DataSource
source.DataSource = usersList;
// And again, set the DataSource of the DataGridView
// Note that this is just example code, and the BindingList<User>
// DataSource setting is gone. You wouldn't do this in the real world
dataGridView1.DataSource = source;
dataGridView1.AllowUserToAddRows = true;
}
// This button click event handler shows how to add a new row, and
// get at the inserted object to change its values.
private void button1_Click(object sender, EventArgs e)
{
User user = (User)source.AddNew();
user.Name = "Mary Poppins";
}
}
答案 1 :(得分:2)
您可以订阅OnUserAddedRow和OnUserDeletedRow个活动,以便您可以根据用户操作修改您的收藏。