Reputation: 153
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
Upvotes: 0
Views: 342
Reputation: 1063338
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
}
Upvotes: 5
Reputation: 38618
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();
Upvotes: 2