我如何从C#中的数据表中读取一行?

时间:2016-07-25 01:29:01

标签: c# datatable

我正在寻找一种从数据表中读取行的简单方法。我确信这已经在某个地方得到了回答,但对于我的生活我无法找到它。

我的代码如下:

static void Main(string[] args)
        {
            DataTable table1 = new DataTable("myTable");
            DataColumn column;
            DataRow row;

        table1.PrimaryKey = new DataColumn[] { table1.Columns["idnum"] };

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.AutoIncrement = false;
        column.ColumnName = "name";
        column.ReadOnly = true;
        column.Unique = false;
        table1.Columns.Add(column);

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.AutoIncrement = false;
        column.ColumnName = "type";
        column.ReadOnly = true;
        column.Unique = false;
        table1.Columns.Add(column);

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.Int32");
        column.AutoIncrement = false;
        column.ColumnName = "atk";
        column.ReadOnly = true;
        column.Unique = false;
        table1.Columns.Add(column);

        column = new DataColumn();
        column.DataType = System.Type.GetType("System.Int32");
        column.AutoIncrement = false;
        column.ColumnName = "spd";
        column.ReadOnly = true;
        column.Unique = false;
        table1.Columns.Add(column);



        row = table1.NewRow();

        row["name"] = "long sword";
        row["type"] = "weapon";
        row["atk"] = 7;
        row["spd"] = 4;
        table1.Rows.Add(row);

        row = table1.NewRow();

        row["name"] = "short sword";
        row["type"] = "weapon";
        row["atk"] = 5;
        row["spd"] = 5;
        table1.Rows.Add(row);

        row = table1.NewRow();

        row["name"] = "dagger";
        row["type"] = "weapon";
        row["atk"] = 3;
        row["spd"] = 8;
        table1.Rows.Add(row);

        foreach(DataRow rowly in table1.Rows)
        {
            //what goes here?

        }
        Console.ReadKey();

}

我写什么来查看行中的数据?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码打印这些值:

int rowIndex=0;
StringBuilder rowValueBuilder = new StringBuilder();
foreach (DataRow rowly in table1.Rows)
{       
    rowValueBuilder.AppendFormat("Row {0} Values \n", rowIndex++);
    rowValueBuilder.AppendFormat("Name  : {0} \n", rowly["name"]);
    rowValueBuilder.AppendFormat("Type  : {0} \n", rowly["type"]);
    rowValueBuilder.AppendFormat("Atk   : {0} \n", rowly["atk"].ToString());
    rowValueBuilder.AppendFormat("Spd   : {0} \n", rowly["spd"].ToString());        
}
Console.WriteLine(rowValueBuilder.ToString());