Index (zero based) must be greater than or equal to zero


C# Problem Overview

Hey I keep getting an error:

> Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

My code:

OdbcCommand cmd = new OdbcCommand("SELECT FirstName, SecondName, Aboutme FROM User WHERE UserID=1", cn);

OdbcDataReader reader = cmd.ExecuteReader();
while (reader.Read())
    Name.Text = String.Format("{0} {1}", reader.GetString(0), reader.GetString(1));
    Aboutme.Text = String.Format("{2}", reader.GetString(0));

C# Solutions

Solution 1 - C#

Your second String.Format uses {2} as a placeholder but you're only passing in one argument, so you should use {0} instead.

Change this:

String.Format("{2}", reader.GetString(0));

To this:

String.Format("{0}", reader.GetString(2));

Solution 2 - C#

In this line:

Aboutme.Text = String.Format("{2}", reader.GetString(0));

The token {2} is invalid because you only have one item in the parms. Use this instead:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Solution 3 - C#

Change this line:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Solution 4 - C#

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);


Solution 5 - C#

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Solution 6 - C#

using System;

namespace ConsoleApp1
    class Program
        static void Main()
            Console.WriteLine("Enter Your FirstName ");
            String FirstName = Console.ReadLine();

            Console.WriteLine("Enter Your LastName ");
            String LastName = Console.ReadLine();

            Console.WriteLine("Hello {0}, {1} ", FirstName, LastName);


Solution 7 - C#

Change this line:

The 2 should be 0. Every count starts at 0.

//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong

//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionG GrView Question on Stackoverflow
Solution 1 - C#Ahmad MageedView Answer on Stackoverflow
Solution 2 - C#jfollasView Answer on Stackoverflow
Solution 3 - C#Mike ColeView Answer on Stackoverflow
Solution 4 - C#SkeetJonView Answer on Stackoverflow
Solution 5 - C#Kashif FarazView Answer on Stackoverflow
Solution 6 - C#paragView Answer on Stackoverflow
Solution 7 - C#SAAD KView Answer on Stackoverflow