C#向DataTable添加数据
时间: 2023-07-12 10:28:55 浏览: 119
在 C# 中向 DataTable 添加数据可以使用以下代码示例:
```csharp
// 创建 DataTable
DataTable dt = new DataTable("MyDataTable");
// 添加列
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
// 添加数据行
dt.Rows.Add(1, "Tom", 20);
dt.Rows.Add(2, "Jerry", 22);
dt.Rows.Add(3, "Alice", 25);
```
其中,`dt.Columns.Add` 方法用于添加列,可以指定列名和列类型。`dt.Rows.Add` 方法用于添加数据行,可以按照列顺序传入数据值。
相关问题
C# DataTable 插入多行数据
可以使用以下两种方法向C# DataTable中插入多行数据:
方法一:使用DataTable的Rows.Add方法
```csharp
// 创建DataTable
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
// 插入多行数据
dt.Rows.Add("Tom", 18);
dt.Rows.Add("Jerry", 20);
dt.Rows.Add("Lucy", 22);
```
方法二:使用DataTable的LoadDataRow方法
```csharp
// 创建DataTable
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
// 定义多行数据
object[] row1 = { "Tom", 18 };
object[] row2 = { "Jerry", 20 };
object[] row3 = { "Lucy", 22 };
// 插入多行数据
dt.LoadDataRow(row1, true);
dt.LoadDataRow(row2, true);
dt.LoadDataRow(row3, true);
```
C# 向datatable中赋值
要向 DataTable 中赋值,可以使用以下步骤:
1. 创建一个 DataTable 对象并定义列的结构:
```csharp
DataTable dt = new DataTable();
dt.Columns.Add("Column1", typeof(int));
dt.Columns.Add("Column2", typeof(string));
```
2. 创建 DataRow 对象并将值赋给每一列:
```csharp
DataRow row = dt.NewRow();
row["Column1"] = 1;
row["Column2"] = "Value";
```
3. 将 DataRow 添加到 DataTable 中:
```csharp
dt.Rows.Add(row);
```
你可以根据需要重复步骤2和3,添加多行数据到 DataTable 中。最后,你可以使用 DataTable 来进行数据操作和访问。
这是一个简单的示例,你可以根据你的实际需求进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)