122
votes

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));
}
7
You transposed the index of the argument in the reader with the index of the parameter in the format statement. Switch 2 with 0 in your Aboutme.Text = . - tvanfosson
String.Format does not use unique placeholders per-class nor per-solution. It is per string each time String.Format is called, so please don't increase it to {2} based on {0} and {1} having been used! - RichardTheKiwi
any reason you're using ODBC vs. the .NET connector ? - Jon Black
Why do you use a string.formar for this row :) Aboutme.Text = String.Format("{2}", reader.GetString(0)); you could. Aboutme.Text =reader.GetString(0); - Ivo

7 Answers

200
votes

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));
25
votes

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));
8
votes

Change this line:

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

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);

}
3
votes

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

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

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
1
votes
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.ReadLine();

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

        }
    }
}

Picture