在 C# 中,DataTable
是一个非常灵活的数据结构,用于在内存中表示表格数据。您可以自定义列名和数据内容,以便根据需要创建和填充数据表。下面是如何创建一个带有自定义列名和数据内容的 DataTable
的示例:
1. 创建 DataTable
首先,我们需要创建一个 DataTable
实例,并定义它的列名和数据类型。
Csharp
深色版本
1using System;
2using System.Data;
3
4class Program
5{
6 static void Main()
7 {
8 // 创建 DataTable
9 DataTable table = new DataTable("MyTable");
10
11 // 添加列
12 table.Columns.Add("Name", typeof(string));
13 table.Columns.Add("Age", typeof(int));
14 table.Columns.Add("City", typeof(string));
15 }
16}
2. 添加行和数据
接下来,我们可以添加行和填充数据。
Csharp
深色版本
1// 添加行
2table.Rows.Add("Alice", 30, "New York");
3table.Rows.Add("Bob", 25, "Los Angeles");
4table.Rows.Add("Charlie", 22, "Chicago");
3. 访问数据
一旦数据填充完毕,我们就可以访问数据表中的数据了。
Csharp
深色版本
1// 遍历数据表
2foreach (DataRow row in table.Rows)
3{
4 Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}, City: {row["City"]}");
5}
4. 示例代码
下面是一个完整的示例代码,展示了如何创建和使用带有自定义列名和数据内容的 DataTable
:
Csharp
深色版本
1using System;
2using System.Data;
3
4class Program
5{
6 static void Main()
7 {
8 // 创建 DataTable
9 DataTable table = new DataTable("MyTable");
10
11 // 添加列
12 table.Columns.Add("Name", typeof(string));
13 table.Columns.Add("Age", typeof(int));
14 table.Columns.Add("City", typeof(string));
15
16 // 添加行
17 table.Rows.Add("Alice", 30, "New York");
18 table.Rows.Add("Bob", 25, "Los Angeles");
19 table.Rows.Add("Charlie", 22, "Chicago");
20
21 // 遍历数据表
22 foreach (DataRow row in table.Rows)
23 {
24 Console.WriteLine($"Name: {row["Name"]}, Age: {row["Age"]}, City: {row["City"]}");
25 }
26 }
27}
5. 使用 DataColumn 和 DataRow
如果您需要更细粒度的控制,可以使用 DataColumn
和 DataRow
对象来创建和填充 DataTable
。
Csharp
深色版本
1// 创建 DataColumn 对象
2DataColumn nameColumn = new DataColumn("Name", typeof(string));
3DataColumn ageColumn = new DataColumn("Age", typeof(int));
4DataColumn cityColumn = new DataColumn("City", typeof(string));
5
6// 添加 DataColumn 到 DataTable
7table.Columns.Add(nameColumn);
8table.Columns.Add(ageColumn);
9table.Columns.Add(cityColumn);
10
11// 创建 DataRow 对象
12DataRow aliceRow = table.NewRow();
13aliceRow["Name"] = "Alice";
14aliceRow["Age"] = 30;
15aliceRow["City"] = "New York";
16
17// 添加 DataRow 到 DataTable
18table.Rows.Add(aliceRow);
6. 使用 DataRowBuilder
DataRowBuilder
提供了一种更方便的方式来创建 DataRow
。
Csharp
深色版本
1// 使用 DataRowBuilder
2using (DataRowBuilder builder = table.NewRow())
3{
4 builder["Name"] = "Alice";
5 builder["Age"] = 30;
6 builder["City"] = "New York";
7 builder.EndEdit();
8}
9
10// 添加 DataRow 到 DataTable
11table.Rows.Add(builder.GetRow());
注意事项
- 确保在添加行之前定义好所有的列。
- 使用
typeof
关键字指定列的数据类型。 - 可以使用
DataRow
的索引器来访问列的值。