Problem with reader

D

Dmitri Manushin

hi all.
this is my code

%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection myConn2 = new SqlConnection("server =localhost;
UID=***;PWD=***;database=forum");
SqlCommand myComm2 = new SqlCommand("SELECT Replace(body,char(13),'<br>')
from Posts",myConn2);
myConn2.Open();
SqlDataReader myRead = myComm2.ExecuteReader();
while(myRead.Read())
{
Response.Write(myRead["Body"]);
}
myRead.Close();
myConn2.Close();
}

So, when i try execute this code i return error

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: Body

Source Error:

Line 10: while(myRead.Read())
Line 11: {
Line 12: Response.Write(myRead["Body"]);
Line 13: }
Line 14: myRead.Close();


Any idea?

P.S.

If i use datareader everything is ok.

Thanks.
 
K

Kevin Spencer

You didn't alias the field. You aren't selecting the "Body" field from the
table. You're creating a new derived column from it. Use an alias for the
column:

SELECT Replace(body,char(13),'<br>') As Body from Posts

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
http://www.takempis.com
Neither a follower nor a lender be.

Dmitri Manushin said:
hi all.
this is my code

%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection myConn2 = new SqlConnection("server =localhost;
UID=***;PWD=***;database=forum");
SqlCommand myComm2 = new SqlCommand("SELECT
Replace(body said:
from Posts",myConn2);
myConn2.Open();
SqlDataReader myRead = myComm2.ExecuteReader();
while(myRead.Read())
{
Response.Write(myRead["Body"]);
}
myRead.Close();
myConn2.Close();
}

So, when i try execute this code i return error

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: Body

Source Error:

Line 10: while(myRead.Read())
Line 11: {
Line 12: Response.Write(myRead["Body"]);
Line 13: }
Line 14: myRead.Close();


Any idea?

P.S.

If i use datareader everything is ok.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top