Kirsty White
Kirsty White

Reputation: 1220

Index Zero issue with sql

I keep running into a problem with my sql:

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

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

Not sure if its my String.Format?

Upvotes: 1

Views: 110

Answers (4)

phoog
phoog

Reputation: 43056

There is a better solution than that proposed by the accepted answer. Note that the statement ...

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

... passes the format string and some string value to String.Format, which analyzes the format string, calls ToString() on the string value, and then inserts that value into the result at the position indicated by the sequence {0}. Then, of course, it returns the constructed string as its result. Because the format string is "{0}", the constructed string will have the same value as the argument.

Both the written code and the executed algorithm will be simpler if you write this:

Aboutme.Text = reader.GetString(0);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502546

The problem isn't the index for SQL, it's the index for string.Format. This should be evident in the stack trace, which will point to string.Format rather than reader.GetString. Looking carefully at stack traces can save you all manner of effort :)

Of course you don't really need to format at all here (given that you'll just end up with the input string), and I suspect you want column 2. (My guess is that that's where the error came from, after all.)

Aboutme.Text = reader.GetString(2);

If you really want to use string.Format:

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

Upvotes: 0

Fid
Fid

Reputation: 568

My guess would be the second line of code

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

The String.Format, is looking for 3 parameters in that case, {0}, {1} and finally {2}. You have only one.

You should write it has :

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

Upvotes: 2

Icarus
Icarus

Reputation: 63962

Yes, the second line should be again 0 for string.Format:

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

Upvotes: 4

Related Questions