简体   繁体   中英

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. How do I enter the values of a specific column into console.write?

A lot of the information from here is applicable: Getting datarow values into a string?

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:

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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