I am populating DDL’s in asp.net web forms and use a sqlutilility class that I have for all my sql classes that call my stored procedures.
But on each drop down list I keep repeating the same code and renameing it and then calling it when I want to use it.
What I want to know is. is there a way using this code instead of repeating it all the time?
protected void Populate_Authority()
{
// Init()
// ------
SqlConnection conn = null;
SqlDataReader rdr = null;
SqlCommand cmd = null;
//
drp_Authority.Items.Clear();
try
{
// Conn
// ----
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
conn.Open();
// Cmd
// ---
cmd = new SqlCommand("[sp_Populate_Authority]", conn);
cmd.CommandType = CommandType.StoredProcedure;
// Execute
// -------
rdr = cmd.ExecuteReader();
// Row(s)?
// -------
if (rdr.HasRows)
{
// Read
// ----
while (rdr.Read())
{
// Populate
// --------
drp_Authority.Items.Add(
new ListItem(
rdr["Authority"].ToString(),
rdr["AuthorityID"].ToString()));
}
// Blank
// -----
drp_Authority.Items.Insert(0, String.Empty);
}
// Clean up / Close down
// ---------------------
cmd.Dispose();
rdr.Dispose();
rdr.Close();
conn.Dispose();
conn.Close();
}
catch (SqlException ex)
{
// Throw Sql Exception
// -------------------
throw ex;
}
finally
{
// Clean up / Close down
// ---------------------
if (cmd != null)
{
cmd.Dispose();
}
if ((rdr != null) && (!rdr.IsClosed))
{
rdr.Dispose();
rdr.Close();
}
if ((conn != null) && (conn.State != ConnectionState.Closed))
{
conn.Dispose();
conn.Close();
}
}
}
Take your code, wrap it in a helper method:
Then call it from your code:
And repeat for all ddl’s.