通过DataGridView向集合添加元素

时间:2011-04-20 13:47:27

标签: c# .net winforms datagridview

我将DataGridView控件绑定到List集合。所以,我可以编辑集合的元素。有没有办法使用此网格启用删除和添加元素?

2 个答案:

答案 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)

您可以订阅OnUserAddedRowOnUserDeletedRow个活动,以便您可以根据用户操作修改您的收藏。