I'm new to C# but have managed to piece together an SQLCommand query. However , I can't for the life of me figure out how to get it to display all columns. The below code is what i have currently (it successfully shows the first 5 columns):
Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3} \t| {4} \t",
reader[0], reader[1], reader[2], reader[3], reader[4]));
What is the simplest way to show ALL columns without having to list each one like I did above? Also, is there a way to specifically name the columns that i want to display? for example, the below successfully shows the "company" column but I cant figure out how to do multiple columns specifically. What if i wanted to show "company" and "FiscalYear"?:
Console.WriteLine(reader["Company"].ToString());
I researched this for about 2 hours but was unable to come up with a solution. thank you very much for your help!
You can use a StringBuilder to create the text in a loop
var sb = new StringBuilder();
for (int i = 0; i < reader.FieldCount; i++) {
sb.Append($"{reader[i]} \t |");
}
sb.Length -= 4; // Remove the last " \t |".
Console.WriteLine(sb);
sb.Append(something) is more efficient than s = s + something, because string concatenations always create a new string object and copy the old string to the new one before appending something. Whereas the StringBuilder works with a buffer and can append several times until the buffer is full and must be resized.
The $ stands for string interpolation. These two lines are equivalent:
String.Format("{0}, {1}, {2}", a, b, c)
$"{a}, {b}, {c}"
If your reader variable is an instance of SqlDataReader, you could do something like this:
void Main()
{
SqlDataReader reader = getDataReader(); \\Code that returns a data reader
Console.WriteLine(createOutputString(reader));
}
private string createOutputString(SqlDataReader reader)
{
//Create an array to hold all the values of the reader
object[] values = new object[reader.FieldCount];
//Fill the array with the values
reader.GetValues(values);
//Return a string with each value of the array separated by a delimiter
return string.Join(" \t | ", values);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With