views:

52

answers:

5

I have a SQL Server 2008 database and I am working on it in the backend. I am working on asp.net/C#

SqlDataReader rdr = cmd.ExecuteReader();  
while (rdr.Read())  
{              
   //how do I read strings here????  
}  

I know that the reader has values. My SQL command is to select just 1 column from a table. The column contains strings ONLY. I want to read the strings (rows) in the reader one by one. How do I do this?

Thanks

+2  A: 
string col1Value = rdr["ColumnOneName"].ToString();

or

string col1Value = rdr[0].ToString();

edit: These are objects, so you need to either cast them or .ToString()

Mark Avenius
the [] operator returns a object, you will need to cast it as a string.
Scott Chamberlain
+2  A: 

Put the name of the column begin returned from the database where "ColumnName" is. If it is a string, you can use .ToString(). If it is another type, you need to convert it using System.Convert.

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    string column = rdr["ColumnName"].ToString();
    int columnValue = Convert.ToInt32(rdr["ColumnName"]);
}
Martin
+3  A: 
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    var myString = rdr.GetString(0);
    // Do somthing with this rows string, forexample to put them in to a list
    ListDeclaredElsewhere.Add(myString);
}
Scott Chamberlain
A: 

In the simplest terms, if your query returns column_name and it holds a string:

while (rdr.Read())
{
    string yourString = rdr.getString("column_name")
}
Dekker500
A: 

thanks everyone. I actually figured out that I could do this:

while (rdr.read()) {
string str = rdr.GetValue().Tostsring().Trim();
}

VP