Adding elements to the collection through DataGridView
I bounded DataGridView control to the List collection. So, I can edit elements of the collection. Is there any way to enable removing and adding e开发者_如何学Pythonlements to the collection using this grid?
The generic List<T>
does not fully support binding to the DataGridView
, as you can see you can edit items in the list but not add or remove.
What you need to use is either a BindingList<T>
or a BindingSource
.
The BindingList<T>
will allow you to use the UI to add and delete rows from the grid - when you change you DataSource
to this you will see the blank new row at the botton of the grid. You still cannot programatically add or remove rows. For that you need a BindingSource
.
An example of both is below (using an example Users class, but the detail of that isn't important here).
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";
}
}
There are OnUserAddedRow and OnUserDeletedRow events that you can subscribe to so that you could modify your collection on user action.
精彩评论