Search code examples
.netfunctioncode-behind

Repeating CodeBehind code in .NET


I have a column on my web site for showing recent news.

Here's the code I use in my CB file.

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;

    public partial class LearnMore : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Define database connection
            SqlConnection conn = new SqlConnection("Server=\\SqlExpress;Database=;Integrated Security=True");
            // Create command
            SqlCommand comm = new SqlCommand("SELECT id, title FROM news", conn);
            // Open connection
            conn.Open();
            // Execute the command
            SqlDataReader reader = comm.ExecuteReader();
            // Read and display the data
            while (reader.Read())
            {
                newsLabel.Text += "<a href='NewsEntry.aspx?ID=" + reader["ID"] + "'>" + reader["Title"] + "</a>" + "<br />";
            }
            // Close the reader and the connection
            reader.Close();
            conn.Close();
        }
    }

I'm using the above code in every CodeBehind file.

Would it make more sense to have this in just one place? And if "YES!", how do I go about this?

Many thanks for any help with this.


Solution

  • Yes, it would make sense.

    Create a base page that has this in it and have all other pages inherit from that.

    public partial class BasePage : System.Web.UI.Page
    {
      // code that is used in all pages
    }
    
    public partial class LearnMore : BasePage
    {
      // code for LearnMore
    }