The proper way would be to do a number of things:
- wrap your disposable objects into
using blocks
- use a separate
SqlCommand object and use a parametrized query (instead of concatenating together your SQL)
- since you're only returning a single set of data - use a
DataTable instead of the much "heavier" DataSet
- separate the fetching of the data into its own method - and just call the from your web page - makes it universally useable, too! (will work for other things - not just
CanadaProvinces)
So your code should be something like this:
private DataTable FetchData(string categoryValue)
{
string query = "SELECT [Key], [Value] FROM [data_LookupValues] where Category = @Category";
using (SqlConnection con = new SqlConnection(strConn))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@Category", SqlDbType.VarChar, 50).Value = categoryValue;
SqlDataAdapter myda = new SqlDataAdapter(cmd);
DataTable result = new DataTable();
myda.Fill(result);
return result;
}
}
and then in your ASPX web's code-behind, use something like this:
DataTable tblCanadaProvinces = FetchData('CanadaProvinces');
ddlState.DataSource = tblCanadaProvinces;
ddlState.DataTextField = "Value";
ddlState.DataValueField = "Key";
ddlState.DataBind();
and be done with it. Now you can call your FetchData method to retrieve any possible category in your lookup table!