【发布时间】:2019-09-24 03:30:00
【问题描述】:
我已经从高处和低处搜索了一种方法来显示 C# 数据表的整行,既可以通过引用行号,也可以通过简单地将行内容写入字符串变量并在控制台中显示字符串。我可以指定确切的行和字段值并显示该值,但不能显示整行。这不是 C# 中的列表,这是一个数据表。
对于下面的简单代码,我为第一个 WriteLine 得到的输出是“Horse”,但后两个 WriteLine 命令,我得到的是“System.Data.DataRow”的控制台输出,而不是整行数据。
我做错了什么?任何帮助将不胜感激。
using System;
using System.Data;
using System.Threading;
namespace DataTablePractice
{
class Program
{
static void Main(string[] args)
{
// Create a DataTable.
using (DataTable table = new DataTable())
{
// Two columns.
table.TableName = "table";
table.Columns.Add("Number", typeof(string));
table.Columns.Add("Pet", typeof(string));
// ... Add two rows.
table.Rows.Add("4", "Horse");
table.Rows.Add("10", "Moose");
// ... Display first field of the first row in the console
Console.WriteLine(table.Rows[0].Field<string>(1));
//...Display the first row of the table in the console
Console.WriteLine(table.Rows[0]);
//...Create a new row variable to add a third pet
var newrow = table.Rows.Add("15", "Snake");
string NewRowString = newrow.ToString();
//...Display the new row of data in the console
Console.WriteLine(NewRowString);
//...Sleep for a few seconds to examine output
Thread.Sleep(4000);
}
}
}
}
【问题讨论】:
-
检查
table.Rows[0]in the debugger。注意它不是任何类型的字符串?如果你想连接这一行的字符串字段值,你必须自己做;有many ways of doing this。
标签: c# datatable row console.writeline