0

How can I generate an array of string that will contain all the column info. this query will return a single row with multiple columns

var rowLines = new List<string>();

        try
        {
            using (SqlConnection connection = new SqlConnection(GetConnectionString()))
            {
                string query = "SELECT I1,I2,I3,I4,I5,I6,I7,I8,I9,I10,I11,I12,I13,I14,I15 FROM LABEL_OUT WHERE LABEL_NAME='" + labelName + "'";
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    connection.Open();

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            rowLines.Add(reader[0].ToString());
                        }

                    }
                }
            }

        }
        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.Message);
        }

here rowLines will Contain all the column value such as I1,I2,.....I15

7
  • You should also put your SqlConnection and your SqlCommand inside a using block to ensure correct resource release. Commented Sep 4, 2018 at 13:15
  • 1
    You're already adding the first column to your list. What is the issue? Add the other columns the same way. Commented Sep 4, 2018 at 13:16
  • Or use a dataset Commented Sep 4, 2018 at 13:17
  • I think you forgot to tell what is the expected output Commented Sep 4, 2018 at 13:18
  • 2
    @DreamTeK the number of times DataSet is a good solution to any problem is vanishingly small... Commented Sep 4, 2018 at 13:22

2 Answers 2

5

Probably the easiest way to do this is to use DbDataReader.GetValues(object[]), which populates a pre-existing array with the values from each column:

var vals = new object[reader.FieldCount];
while (reader.Read())
{
    reader.GetValues(vals);
    // ... do something with the values
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you are sure that you will take a single line you could loop on the reader using the FieldCount and add each element on a List<string>. Finally, you could just return it as an array.

var rowLines = new List<string>();

if (reader.Read())
{
   for (int i = 0; i < reader.FieldCount; i++)
   {
      rowLines.Add(reader.IsDBNull(i) ? string.Empty : reader[i].ToString());
   }
}

return rowLines.ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.