C# 将数据写入DataGridView 中并显示
时间: 2024-03-23 10:40:08 浏览: 31
您可以使用以下代码将数据写入 DataGridView 中并显示:
```csharp
// 创建 DataTable 对象
DataTable table = new DataTable();
// 添加列
table.Columns.Add("姓名");
table.Columns.Add("年龄");
// 添加行数据
table.Rows.Add("张三", 20);
table.Rows.Add("李四", 25);
table.Rows.Add("王五", 30);
// 将 DataTable 绑定到 DataGridView 中
dataGridView1.DataSource = table;
```
上述代码中,我们首先创建了一个 DataTable 对象,并添加了两列,然后添加了三行数据。最后,将 DataTable 对象绑定到 DataGridView 中显示。您可以根据自己的需要修改列名、行数据等信息。
相关问题
winform 将数据写入datagridview的第3列中
你可以通过以下代码将数据写入 DataGridView 的第3列中:
```C#
// 假设 DataGridView 的名称为 dataGridView1
// 假设要写入的数据为 data
// 假设要写入的行索引为 rowIndex
// 设置第3列的值为 data
dataGridView1.Rows[rowIndex].Cells[2].Value = data;
```
其中,`Rows[rowIndex]` 表示要写入数据的行,`Cells[2]` 表示要写入数据的列(列的索引是从0开始计数的,因此第3列的索引为2)。`Value` 属性表示要写入的数据。
winform 将5组数据写入datagridview的行中
你可以通过以下代码将5组数据写入 DataGridView 的5行中:
```C#
// 假设 DataGridView 的名称为 dataGridView1
// 假设要写入的数据为 data
// 假设要从第1行开始写入
for (int i = 0; i < 5; i++)
{
// 设置第1列的值为 i + 1
dataGridView1.Rows[i].Cells[0].Value = i + 1;
// 设置第2列的值为 data[i]
dataGridView1.Rows[i].Cells[1].Value = data[i];
}
```
其中,`Rows[i]` 表示要写入数据的行,`Cells[0]` 和 `Cells[1]` 分别表示要写入数据的第1列和第2列。循环从0开始,写入了5行数据。你可以根据需要修改行的起始索引和要写入的数据,来满足你的需求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)