I am trying to use iteration in C# to clean up what would be otherwise a lengthy repetitive process of writing the same query but with one different parameter and binding data etc..
However I am having a problem with using the same reader.
This is my code at the moment:
private void bindData()
{
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
for (int i = 0; i < 7; i++)
{
SqlCommand command = new SqlCommand("SELECT Name AS 'Class Name', FirstName AS 'Instructor First Name', LastName AS 'Instructor Last Name', LessonDuration AS 'Lesson Duration (hrs)', LessonTime AS 'Lesson Start' FROM Lesson, Class, Instructor WHERE Lesson.ClassID = Class.ClassID AND Lesson.InstructorID = Instructor.InstructorID AND LessonDay = '@Day';", connection);
command.Parameters.AddWithValue("@Day", days[i]);
using(SqlDataReader dr = command.ExecuteReader())
{
switch (days[i])
{
case "Monday":
GridView1.DataSource = dr;
DataBind();
break;
case "Tuesday":
GridView2.DataSource = dr;
DataBind();
break;
case "Wednesday":
GridView3.DataSource = dr;
DataBind();
break;
case "Thursday":
GridView4.DataSource = dr;
DataBind();
break;
case "Friday":
GridView5.DataSource = dr;
DataBind();
break;
case "Saturday":
GridView6.DataSource = dr;
DataBind();
break;
case "Sunday":
GridView7.DataSource = dr;
DataBind();
break;
}
dr.Close();
}
}
connection.Close();
}
}
As you can see, the point is to bind different queries to different grid views that represent different days of the week.
I keep getting errors of either "Invalid fieldcols data reader is closed" or "Please close before reading again" (if the dr.close(); is removed).
Is there a solution to this problem? Thank you.