繁体   English   中英

遍历数据表中的特定列

[英]Looping through a specific column from a datatable

我有以下代码:

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中输入特定列的值?

这里有很多信息适用:将datarow值转换为字符串?

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

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类,这样就不会浪费资源一遍又一遍地进行字符串连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM