用C#写一个DataGridView控件动态添加行和列的方法,包括设置列的属性,列有下拉、文本、时间、数值等类型 ,列控件绑定数据源
时间: 2023-12-10 08:40:36 浏览: 262
以下是一个示例代码,实现了动态添加行和列,并设置列的属性,包括下拉、文本、时间、数值等类型。同时,列控件绑定了数据源。
```csharp
// 创建一个 DataGridView 控件
DataGridView dataGridView1 = new DataGridView();
// 添加列
DataGridViewColumn column1 = new DataGridViewComboBoxColumn();
column1.HeaderText = "下拉框列";
column1.Name = "column1";
column1.DataSource = new string[] { "选项1", "选项2", "选项3" };
dataGridView1.Columns.Add(column1);
DataGridViewColumn column2 = new DataGridViewTextBoxColumn();
column2.HeaderText = "文本列";
column2.Name = "column2";
dataGridView1.Columns.Add(column2);
DataGridViewColumn column3 = new DataGridViewTextBoxColumn();
column3.HeaderText = "时间列";
column3.Name = "column3";
column3.ValueType = typeof(DateTime);
dataGridView1.Columns.Add(column3);
DataGridViewColumn column4 = new DataGridViewTextBoxColumn();
column4.HeaderText = "数值列";
column4.Name = "column4";
column4.ValueType = typeof(decimal);
dataGridView1.Columns.Add(column4);
// 添加行
dataGridView1.Rows.Add("选项1", "文本", DateTime.Now, 100);
dataGridView1.Rows.Add("选项2", "文本", DateTime.Now.AddDays(1), 200);
dataGridView1.Rows.Add("选项3", "文本", DateTime.Now.AddDays(2), 300);
// 设置列控件绑定数据源
((DataGridViewComboBoxColumn)dataGridView1.Columns[0]).DisplayMember = "Name";
((DataGridViewComboBoxColumn)dataGridView1.Columns[0]).ValueMember = "Value";
((DataGridViewComboBoxColumn)dataGridView1.Columns[0]).DataSource = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("选项1", "1"),
new KeyValuePair<string, string>("选项2", "2"),
new KeyValuePair<string, string>("选项3", "3")
};
```
阅读全文