I just have a very simple n00b question so please forgive me. Basically I have an ASP.NET website connected to an SQL server database. Everything is working fine (I can connect to the database, execute queries) but where should I put the SQL connection/logic code? In the aspx.cs code of the corresponding web form or create a separate .cs file that lies within the 'App_Code' folder? My intention is to read from the database and populate a 'GridView' on the corresponding web form.

I have always been told to 'separate' logic code from user interface code and to satisfy this rule I currently have the query execution code in a .cs file which lies in the 'App_Code' folder. I'm drawing a blank though on how to read each field from my database and populate the 'GridView' object in my aspx.cs form code. Obviously I could do 'get' and 'set' methods for each field in my database but this seems a bit to excessive.

Could someone elaborate on where I should put it? I have attached a sample of my code below that rests in the .cs file.

I would appreciate any insight on how/where to put this code. Or perhaps a little elaboration on where to draw the line between 'UI' code and 'logic' code.

public void connectToDb()
        //uses the connection parameters defined in web.config
        string connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
        //open up a database connection
        SqlConnection sqlConnection = new SqlConnection(connectionString);

            //open the connection
            //simple select all query from TABLE 'Inventory'
            SqlCommand command = new SqlCommand("SELECT * FROM Inventory", sqlConnection);
            SqlDataReader reader = command.ExecuteReader();

            //Read info
            while (reader.Read())
                //This is where I read info from the database
                int year = (int)reader["year"];
                string model = (string)reader["model"];
                float price = (float)reader["price"];
                //..more variables defined but didn't want to list
        catch (Exception e)

under your <configSections> in web.conf

		<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
		<add name="MasterSQLConnectionString" connectionString="Data Source=DALSQL1\GMC;Initial Catalog=MasterSQL;Persist Security Info=True;User ID=unasdf;Password=xxxx" providerName="System.Data.SqlClient"/>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.