G Gr
G Gr

Reputation: 6090

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

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

Upvotes: 134

Views: 323831

Answers (7)

parag
parag

Reputation: 11

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

Upvotes: 1

SAAD K
SAAD K

Reputation: 51

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

Upvotes: 1

Kashif Faraz
Kashif Faraz

Reputation: 331

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

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

Upvotes: 3

SkeetJon
SkeetJon

Reputation: 1491

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

}

Upvotes: 7

Ahmad Mageed
Ahmad Mageed

Reputation: 96507

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

Upvotes: 220

jfollas
jfollas

Reputation: 1235

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

Upvotes: 27

Mike Cole
Mike Cole

Reputation: 14743

Change this line:

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

Upvotes: 8

Related Questions