[英]Looping through a specific column from a datatable
I have the following code: 我有以下代码:
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
}
}
}
}
}
Works fine. 工作正常。 However, I don't understand how to replace that comment section. 但是,我不知道如何替换该注释部分。 I basically want to read in rows from a specific column in the foreach loop. 我基本上想从foreach循环的特定列中读取行。 How do I enter the values of a specific column into console.write? 如何在console.write中输入特定列的值?
A lot of the information from here is applicable: Getting datarow values into a string? 这里有很多信息适用:将datarow值转换为字符串?
You can get a particular column value using: 您可以使用以下方法获取特定的列值:
row["ColumnName"]
So, for example, if you were writing to the console the value of "FirstName" for every row, it might look like: 因此,例如,如果您要向控制台写入每一行的“ FirstName”值,则可能类似于:
foreach (DataRow row in datatable.Rows)
{
Console.Write(intTest);
Console.Write(Environment.NewLine);
intTest += 1;
Console.WriteLine(row["FirstName"]);
}
The post I referenced above mentions the ItemArray property if that is more applicable to your situation. 我上面引用的帖子提到了ItemArray属性(如果它更适合您的情况)。 And @Daniel's comment above about the Field property is good too since my example above assumes you know the type is string, which of course is a big assumption. @Daniel上面关于Field属性的评论也很好,因为上面的示例假定您知道类型为字符串,这当然是一个很大的假设。
Of course, you'll always want to make sure to check that the column exists so you don't get an error. 当然,您将始终要确保检查该列是否存在,以免出现错误。 If you're going to build up a large string value by concatenating the value from the column, be sure to use the StringBuilder class so you don't waste resources doing string concatenations over and over. 如果要通过连接列中的值来构建较大的字符串值,请确保使用StringBuilder类,这样就不会浪费资源一遍又一遍地进行字符串连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.