Index was outside the bounds of the array
-
Hi All, I have a datatable and i want to get the first and second characters of a column of each row of my datatable:
foreach (DataRow dr in dt.Rows)
{
string str = dr[5].ToString();
char first = str[0];
char second = str[1];
}Bud i m getting a error: Index was outside the bounds of the array on the 5e line : char second = str[1]; can anyone tell me why and what is the solution? Thanx
-
Hi All, I have a datatable and i want to get the first and second characters of a column of each row of my datatable:
foreach (DataRow dr in dt.Rows)
{
string str = dr[5].ToString();
char first = str[0];
char second = str[1];
}Bud i m getting a error: Index was outside the bounds of the array on the 5e line : char second = str[1]; can anyone tell me why and what is the solution? Thanx
KamarBand wrote:
string str = dr[5].ToString();
You should use the value inside the DataColumn, not the DataColumn itself (let me guess the column name is only 1 character).
xacc.ide - now with TabsToSpaces support
IronScheme - 1.0 alpha 4a out now (29 May 2008) -
Hi All, I have a datatable and i want to get the first and second characters of a column of each row of my datatable:
foreach (DataRow dr in dt.Rows)
{
string str = dr[5].ToString();
char first = str[0];
char second = str[1];
}Bud i m getting a error: Index was outside the bounds of the array on the 5e line : char second = str[1]; can anyone tell me why and what is the solution? Thanx
KamarBand wrote:
Bud i m getting a error: Index was outside the bounds of the array on the 5e line : char second = str[1]; can anyone tell me why and what is the solution?
Yeah, you don't do any bounds checking on the string. In this case it's exactly one character long. If the string is empty, then it'll also crash in
char first = str[0];
regards -
KamarBand wrote:
string str = dr[5].ToString();
You should use the value inside the DataColumn, not the DataColumn itself (let me guess the column name is only 1 character).
xacc.ide - now with TabsToSpaces support
IronScheme - 1.0 alpha 4a out now (29 May 2008)Hi Leppie, thanx fory reply, i found the problem, one of the rows had a empty string, that's why i got the error.