Read data from SqlDataReader Read data from SqlDataReader asp.net asp.net

Read data from SqlDataReader


using(SqlDataReader rdr = cmd.ExecuteReader()){    while (rdr.Read())    {        var myString = rdr.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.        // Do somthing with this rows string, for example to put them in to a list        listDeclaredElsewhere.Add(myString);    }}


string col1Value = rdr["ColumnOneName"].ToString();

or

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

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


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"]);}