c#datagridview数据绑定list
时间: 2023-12-07 16:39:23 浏览: 112
C# datagridview 绑定数据后绑定标题
以下是C#中使用DataGridView控件绑定List的示例代码:
1. 首先定义一个数据类Class1,包含两个属性Name和Age:
```csharp
public class Class1
{
public string Name { get; set; }
public int Age { get; set; }
public Class1(string name, int age)
{
Name = name;
Age = age;
}
}
```
2. 在Form中定义一个List<Class1>类型的变量list,并在构造函数中初始化:
```csharp
public partial class Form1 : Form
{
private List<Class1> list;
public Form1()
{
InitializeComponent();
list = new List<Class1>();
}
}
```
3. 在DataGridView控件的DataBindingComplete事件中绑定数据源:
```csharp
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
dataGridView1.Columns["Name"].HeaderText = "姓名";
dataGridView1.Columns["Age"].HeaderText = "年龄";
}
private void button1_Click(object sender, EventArgs e)
{
list.Add(new Class1("张三", 18));
list.Add(new Class1("李四", 20));
dataGridView1.DataSource = list;
}
```
4. 在DataGridView控件的CellEndEdit事件中更新数据源:
```csharp
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
string name = row.Cells["Name"].Value.ToString();
int age = int.Parse(row.Cells["Age"].Value.ToString());
list[rowIndex].Name = name;
list[rowIndex].Age = age;
}
```
阅读全文