Farrah Farrah - 5 months ago 92
SQL Question

There is already an open DataReader associated with this Connection which must be closed first using c#

I am getting this error "There is already an open DataReader associated with this Connection which must be closed first". I have tried using command but still can't fix this issue. The code I am using is as follows

{
conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
using (MySqlDataAdapter MyAdapter = new MySqlDataAdapter())
{
MyAdapter.SelectCommand = cmd;
using (DataTable dTable = new DataTable())
{
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
}
}
}


I was originally trying below code (without using command).

conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = cmd;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
conn.Close();


But both of the codes are giving exactly the same error (i.e. There is already an open DataReader associated with this Connection which must be closed first.)
Your help would be really appreciated.
Thanks in advance!

Answer

This line creates a DataReader that you're not closing:

cmd.ExecuteReader();

Just remove the whole line, it's useless in your case.