Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing a DataReader

Status
Not open for further replies.

developer155

Programmer
Jan 21, 2004
512
US
Hello,
I am passing a DataReader object to a calling methid but when I try to get the data out of DataReader in the calling methid I get the error that data does not exist
I know that the connection has to be open and I did make sure that it is. I can go through the records in the methid that creates the reader, but not in the method that calls it.
Here is my code:

Public Class Conn
{

public SqlDataReader GetData(string strStatement)
{
SqlDataReader dr = null;

try
{

SqlCommand cmd = new SqlCommand(strStatement, cn1);
cn1.Open();

dr = cmd.ExecuteReader();
while(dr.Read())
{
Console.WriteLine(dr.GetString(0));//this works fine!

}
}
catch (System.Exception e)
{
System.Console.WriteLine(e.Message.ToString());
return null;

}
return dr;
}

Now this is the calling procedure:

string strPropSelect="SELECT * FROM TMYTABLE";
dr = conn.GetData(strPropSelect);
if (!dr.HasRows)//this is fine
{
System.Console.WriteLine("ERROR: Failed to load property data");
return;
}

//but it errors out below
System.Console.WriteLine(dr.GetString(0));


Thanks for any help!!!
 
Did you omit any code? You will need a dr.Read() somewhere before

System.Console.WriteLine(dr.GetString(0));
 
Yes, I did firget that and that fixed this problem. Now I have another question. I need to be using the data reader in my program (it returns one row and I will be calling a method that shoudl return certain data from the data reader, using column name). So do I have to call Read method every time I want to get some data?
I was gonna use this, please let me know what I need to modify
public string GetField(string strFieldName)
{
string strField;
strField=(string)mydatareader[strFieldName];
return strField;
}

thanks!!!
 
Never mind, I figured it out, one Read() is enough at the beginning

thanks!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top