mellenburg
Programmer
I'm very new to programming in .Net and object-oriented programming. I have a working program that can be refactored by putting repeated lines of code in a single location and the n referencing that piece of code. For example, I have the following code in my OnLoad event:
The SqlConnection line gets used in other places in the code behind file. Rather than have the entire connection string, I'd like to be able to replace the line with something like
GetConnection();
How do I do this?
Matt
Code:
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
SqlConnection sqlConn = new SqlConnection("Data Source=XXXX;Database=XXXX;user id=XXXX;password=XXXX;");
// Retrieve User appointments
SqlCommand sqlGetAppointments = new SqlCommand("MassageGetAppointmentsForUser", sqlConn);
sqlGetAppointments.CommandType = CommandType.StoredProcedure;
sqlGetAppointments.Parameters.Add("@UserID", SqlDbType.VarChar).Value = User.Identity.Name;
sqlConn.Open();
SqlDataReader sqlDRAppointments = sqlGetAppointments.ExecuteReader();
dgMassageAppointments.DataSource=sqlDRAppointments;
dgMassageAppointments.DataBind();
sqlConn.Close();
}
}
GetConnection();
How do I do this?
Matt