C# DataGridView绑定List对象时,利用BindingList来实现增删查改
时间: 2024-01-21 16:01:59 浏览: 387
要利用BindingList来实现DataGridView绑定List对象的增删查改,可以按照以下步骤进行:
1. 定义一个实体类,用于存储数据。例如:
```csharp
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
```
2. 在窗体中定义一个BindingList对象,并初始化为空。例如:
```csharp
private BindingList<User> userList = new BindingList<User>();
```
3. 将BindingList对象绑定到DataGridView上。例如:
```csharp
dataGridView1.DataSource = userList;
```
4. 实现添加功能。例如:
```csharp
private void btnAdd_Click(object sender, EventArgs e)
{
User user = new User();
user.Id = userList.Count + 1;
user.Name = txtName.Text.Trim();
user.Age = int.Parse(txtAge.Text.Trim());
userList.Add(user);
}
```
5. 实现删除功能。例如:
```csharp
private void btnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int index = dataGridView1.SelectedRows[0].Index;
userList.RemoveAt(index);
}
}
```
6. 实现修改功能。例如:
```csharp
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int index = dataGridView1.SelectedRows[0].Index;
User user = userList[index];
user.Name = txtName.Text.Trim();
user.Age = int.Parse(txtAge.Text.Trim());
dataGridView1.Refresh();
}
}
```
7. 实现查询功能。例如:
```csharp
private void btnQuery_Click(object sender, EventArgs e)
{
string name = txtQueryName.Text.Trim();
var queryList = userList.Where(u => u.Name.Contains(name)).ToList();
dataGridView1.DataSource = queryList;
}
```
通过以上步骤,就可以利用BindingList来实现DataGridView绑定List对象的增删查改了。
阅读全文