我将DataGridView控件绑定到List集合。因此,我可以编辑集合的元素。有什么方法可以使用此网格启用将元素删除和添加到集合的功能吗?

最佳答案

通用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";
    }
}

关于c# - 通过DataGridView将元素添加到集合中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5731389/

10-14 16:38
查看更多