C# 从datatable循环通过特定列
我有以下代码:C# 从datatable循环通过特定列,c#,.net,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", Sql
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?此处的许多信息都适用: 可以使用以下方法获取特定列值:
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属性的评论也很好,因为我上面的示例假设您知道类型是string,这当然是一个很大的假设
当然,您总是希望确保检查该列是否存在,以避免出现错误。如果要通过连接列中的值来建立一个大的字符串值,请确保使用StringBuilder类,这样就不会浪费资源反复进行字符串连接。您的意思是如何访问行中的列?i、 例如,
行[“YourColumnName”]
,或者更好的行.Field(“YourColumnName”)
。