Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# datarow

作者:幸福的起点   发布日期:2025-07-27   浏览:3

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // 创建一个 DataTable 对象
        DataTable table = new DataTable();

        // 添加列到 DataTable
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));

        // 创建并添加行到 DataTable
        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        table.Rows.Add(row2);

        // 访问和修改 DataRow
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}");

            // 修改行中的数据
            if ((int)row["ID"] == 1)
            {
                row["Name"] = "Alicia";
            }
        }

        // 删除 DataRow
        table.Rows[0].Delete();
        table.AcceptChanges();

        // 输出最终的 DataTable 内容
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}");
        }
    }
}

解释说明:

  1. 创建 DataTable:我们首先创建了一个 DataTable 对象,它用于表示内存中的表格数据。
  2. 添加列:使用 Columns.Add 方法为 DataTable 添加两列:IDName
  3. 创建并添加行:通过 NewRow 方法创建新的 DataRow 对象,并将其添加到 DataTable 中。
  4. 访问和修改 DataRow:使用 foreach 循环遍历 DataTable 中的所有行,并通过索引器访问和修改行中的数据。
  5. 删除 DataRow:通过 Delete 方法删除指定的行,并调用 AcceptChanges 方法提交更改。
  6. 输出最终结果:再次遍历 DataTable 并输出最终的内容。

这个示例展示了如何在 C# 中使用 DataRow 来操作表格数据。

上一篇:c# tablelayoutpanel

下一篇:c# 替换字符串

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# 取字符串最后一个字符

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站