IndexOutOfRangeException in asp.net

Posted by Dn2010 under ASP.NET on 4/3/2012 | Points: 10 | Views : 8429 | Status : [Member] | Replies : 5
hi friends,


There is no row at position 0.


Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: There is no row at position 0.



OpenConnection(con);
cmd.Connection = con;

SqlDataAdapter da = new SqlDataAdapter("select max(cdate) from emp", con);
DataTable dt = new DataTable();
da.Fill(dt);


if (dt.Rows.Count > 0)
{
Label1.Text = "No Records found!";
}
else
{
Label1.Text = dt.Rows[0][0].ToString();
}

con.Close();


please correct this above code,


thanks.




Responses

Posted by: Self-Innovator on: 4/3/2012 [Member] Bronze | Points: 25

Up
0
Down
Put breakpoint and chek whether data is returning to datatable dt ...
this occurs when thetable doesnt have any row of data

Join Hands Change lives
Thanks & Regards
Straight Edge Society

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sksamantaray on: 4/3/2012 [Member] Silver | Points: 25

Up
0
Down

1)Remove your else part, because if data table has no rows how could you use dt.Rows[0][0].ToString(); ?
keep your custom message here
2)Use Try...Catch and you can show the error in catch block.

There is no row at position 0 means your query does not return any value
System.IndexOutOfRangeException: Because there is no datatable and you are trying to access it.


Thanks,
Sanjay

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Savariya on: 4/4/2012 [Member] Starter | Points: 25

Up
0
Down

if (dt.Rows.Count > 0)
{
Label1.Text = dt.Rows[0][0].ToString();

}
else
{
Label1.Text = "No Records found!";
}

Change this in your code


con.Close();

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ajay.Kalol on: 4/5/2012 [Member] Starter | Points: 25

Up
0
Down
Your IF loop Condition id Wrong,
Change it to


if (dt.Rows.Count > 0)

{
Label1.Text = dt.Rows[0][0].ToString();
}
else
{
Label1.Text = "No Records found!";
}


Ajay
ajaypatelfromsanthal.blogspot.in

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sakthi.Singaravel on: 4/5/2012 [Member] Silver | Points: 25

Up
0
Down
if (dt.Rows.Count <= 0)
{
Label1.Text = "No Records found!";
}
else
{
Label1.Text = dt.Rows[0][0].ToString();
}

con.Close();



Regards,
Singaravel M

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response