I want to pass a method as an argument to remove repetitive code from my program. This is the functionality I would like:
private void sqlQuery(Method sqlMethod)
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
sqlMethod();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
}
finally
{
conn.Close();
}
}
Using:
private void insertTemplate()
{
//create SQL command
SqlCommand insertTemplate = new SqlCommand("INSERT INTO [SavedDescriptionTemplates] (SavedDescription, UserId, CreatedDate) VALUES (@descriptionParam, @userIdParam, @createdDateParam)", conn);
//create and assign parameters
insertTemplate.Parameters.AddWithValue("@descriptionParam", descriptionInput.Text);
insertTemplate.Parameters.AddWithValue("@userIdParam", Int32.Parse(userNameDropDown.SelectedItem.Value));
insertTemplate.Parameters.AddWithValue("@createdDateParam", DateTime.Now);
//execute command and retrieve primary key from the above insert and assign to variable
insertTemplate.ExecuteNonQuery();
}
The call would be:
sqlQuery(insertTemplate());
Is this possible?