I have one table and about 20 columns which contain more than 5000 rows. Right now I want to display all 20 columns in console, and I came to thirth column and I get error
System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'
Here is my code:
using System; using System.Data.SqlClient; namespace DbToJSON { class Program { static void Main(string[] args) { string constring = @"Data Source=(localdb)MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True"; string Query = "select * from AO_ASISTENCA"; SqlConnection conDataBase = new SqlConnection(constring); SqlCommand cmd = new SqlCommand(Query, conDataBase); conDataBase.Open(); using (SqlCommand command = new SqlCommand(Query, conDataBase)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine("{0}", reader.GetString(0)); Console.WriteLine("{0}", reader.GetString(1)); Console.WriteLine("{1}", reader.GetString(0)); } } } } } }
This peace of code make me error
Console.WriteLine("{1}", reader.GetString(0));
When I change this to
Console.WriteLine("{0}", reader.GetString(2));
Anyone can guide me and tell me what’s wrong with this. Maybe I am doing something wrong, but I can not figure out what’s wrong with this. Thanks
Advertisement
Answer
The SQL part is fine, but the format string is wrong:
Console.WriteLine("{1}", reader.GetString(0));
The {1}
in the format string is basically the “second placeholder”, but there was no first. So when you pass it reader.GetString(0)
(or any value) to put in the first placeholder, there is no such placeholder.
You don’t really need a format string at all here, since you’re not formatting anything. On each of your output lines you can just output the string value:
Console.WriteLine(reader.GetString(0)); Console.WriteLine(reader.GetString(1)); // etc.
Generally you’d use a format string when you want to format the output into some overall structure. For example, you could replace your output lines with something like this:
Console.WriteLine("{0} - {1}", reader.GetString(0), reader.GetString(1));
This would put those two values into those two string placeholders, creating a single line of output with the values separated by spaces and a hyphen.