从数据表中循环遍历特定列

时间:2014-07-04 11:58:55

标签: c# .net

我有以下代码:

using (connection = new SqlConnection("sql connection goes here"))
{
    using(command = new SqlCommand(@"SELECT col1, col2, col3 FROM table1 WHERE col1 = @col1 AND col2 = @col2", connection))
    {
        command.Parameters.Add("@col1", SqlDbType.VarChar, 255).Value = TextBox1.Text;
        command.Parameters.Add("@col2", SqlDbType.VarChar, 255).Value = TextBox2.Text;

        using (dataadapter = new SqlDataAdapter(command))
        {
            using (datatable = new DataTable())
            {
                dataadapter.Fill(datatable);

                int intTest = 0;

                foreach (DataRow row in datatable.Rows)
                {
                    Console.Write(intTest);
                    Console.Write(Environment.NewLine);
                    intTest += 1;

                    // replace this with another database query which uses data from above to loop through further sql queries

                }
            }
        }
    }
}

工作正常。但是,我不明白如何替换该评论部分。我基本上想要读取foreach循环中特定列的行。如何在console.write中输入特定列的值?

1 个答案:

答案 0 :(得分:2)

此处的大量信息适用: Getting datarow values into a string?

您可以使用以下方式获取特定列值:

row["ColumnName"]

因此,例如,如果您正在向控制台写入" FirstName"的值。对于每一行,它可能看起来像:

foreach (DataRow row in datatable.Rows)
                {
                    Console.Write(intTest);
                    Console.Write(Environment.NewLine);
                    intTest += 1;
                   Console.WriteLine(row["FirstName"]);

                }

上面引用的帖子提到了ItemArray属性,如果它更适合您的情况。 @ Daniel上面关于Field属性的评论也很好,因为上面的例子假设你知道类型是字符串,这当然是一个很大的假设。

当然,您始终要确保检查该列是否存在,这样您才不会收到错误消息。如果您要通过连接列中的值来构建一个大的字符串值,请确保使用StringBuilder类,这样就不会浪费资源一遍又一遍地进行字符串连接。

相关问题