using System;
using System.Data;
class Program
{
static void Main()
{
// 创建一个 DataTable 并添加一些数据
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Alice");
dt.Rows.Add(2, "Bob");
// 获取指定单元格的值,例如获取第1行(索引为0)的“Name”列的值
string cellValue = GetCellValue(dt, 0, "Name");
Console.WriteLine(cellValue); // 输出: Alice
}
static string GetCellValue(DataTable table, int rowIndex, string columnName)
{
if (table == null || rowIndex < 0 || rowIndex >= table.Rows.Count)
{
return "error";
}
DataRow row = table.Rows[rowIndex];
if (row[columnName] == DBNull.Value)
{
return "error";
}
return row[columnName].ToString();
}
}
DataTable
对象,并添加了两列 (ID
和 Name
) 和两行数据。GetCellValue
,它接受三个参数:DataTable
对象、行索引和列名。该方法用于获取指定单元格的值。GetCellValue
方法中,首先检查 DataTable
是否为空,以及行索引是否有效。如果无效,则返回字符串 "error"
。DataRow
对象获取指定列的值。如果该值是 DBNull.Value
,也返回 "error"
。GetCellValue
方法并输出结果。希望这个示例能帮助你理解如何在 C# 中获取 DataTable
某个单元格的值。
上一篇:c# 入门
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站