Search code examples
asp.netsqldatareaderdatareadermysqldatareader

Can I reset and loop again through MySqlDataReader?


I have a MySqlDataReader object, with the result of this query :

SELECT warehouse, leasing, transportation, maintenance, manpower FROM retail WHERE zone = 'Central' GROUP BY warehouse

And then I loop through the DataReader once,

while (r2.Read())
{
strXml.AppendFormat("<set label = '{0}'></set>",r2["warehouse"].ToString());
}

And now I want to loop through it again...!!

I know that DataReader is only a 'forward-only' object.. But is there any other solution for me here ?

I'm asking, is there any any efficient way to hold data other than MySqlDataReader ?


Solution

  • You can use below :

    using (MySqlConnection connMySql = new MySqlConnection(global.g_connString))
                {
                   MySqlCommand cmd = connMySql.CreateCommand();
                    cmd.CommandText = "selece * from <table>"; 
                    connMySql.Open();
                    using (MySqlDataReader dr = cmd.ExecuteReader())
                    {
                            DataTable dt1 = new DataTable();
                            dt1.Load(dr);
                            // You can use this dt1 anywhere in the code
                     }
    

    // parsing datatable

     DataTable dt = new DataTable();
        if (dt.Rows.Count > 0)
        {
            for (int count = 0; count < dt.Rows.Count; count++)
            {
                string str= dt.Rows[count]["[ColumnName]"].ToString();  
            }
        }