gpt4 book ai didi

c# - 通过DataGridView向集合添加元素

转载 作者:行者123 更新时间:2023-12-02 14:52:00 25 4
gpt4 key购买 nike

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

最佳答案

通用List<T>不完全支持绑定(bind)到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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com