Please keep in mind that I'm new to C# and OOP so I apologize in advance if this seems like an easy question to some. I'm going back through my code and looking for ways to objectify repetitive code and create a class for it so that I can simply reuse the class. That being said, I'm not looking to learn NHibernate or any other ORM just yet. I'm not even looking to learn LINQ. I want to hack through this to learn.
Basically I use the same bit of code to access my database and populate a drop-down list with the values that I get. An example:
protected void LoadSchools()
{
SqlDataReader reader;
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("SELECT * FROM [Schools] ORDER BY [SchoolName] ASC", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
cmbEditSchool.DataSource = reader;
cmbEditSchool.DataBind();
cmbEditSchool.Text = "Please select an existing school to edit...";
if (reader != null) reader.Close();
}
finally
{
conn.Dispose();
}
}
I use this same bit of code, over and over again throughout my program, on different pages. Most often, I'm populating a drop-down list or combo box, but sometimes I will populate a gridview, only slightly altering the query.
My question is how can I create a class that will allow me to call a stored procedure, instead of manually using queries like my example, and populate my different controls? Is it possible to do with only 1 method? I only need to start with selects. I've been reading up on IEnumerable which seems like the appropriate interface to use, but how do I use it?
Edited to add:
I marked Rorschach's answer as THE answer because s/he addressed my IEnumerable question. I also understand the need for a proper DAL and perhaps BLL layer. What I was trying to get to was that. I can build a DAL using datasets and table adapters which, in the end, gets me a strongly typed dataset. However, I feel a bit removed from the code. I was after a straight-forward way of building the DAL myself starting with the code that I gave above. Perhaps I'm not wording my question, or what I'm after, correctly.
At any rate, Rorschach came closest to answering my actual question. Thanks.