I have the following code to populate a dropdownlist:
string strConn = ConfigurationManager.ConnectionStrings["PhoQL"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConn))
{
DataSet ds = new DataSet();
using (SqlDataAdapter myda = new SqlDataAdapter("SELECT [Abrv], [State] FROM [States]", con))
{
myda.Fill(ds)
ddlShipState.DataSource = ds;
}
}
ddlShipState.DataTextField = "State";
ddlShipState.DataValueField = "Abrv";
ddlShipState.DataBind();
I was wondering if there is a more efficient way of doing it. Notice I didn’t have to open and close the connection. Wondering if it makes a difference in my example.
In terms of more efficient I am looking for best code practice for what I have above.
No, but the
DataAdapterdoes it implicitely.MSDN:
But also note that opening and closing is not inefficient when you’re using
Connection-Pooling(default). Because thencon.Openjust means “wait, i need this connection now” andcon.Closemeans “ok, you can reuse it somewhere else now, i’m finished”.So you should always close a connection as soon as you’re finished with it. Otherwise the connection-pool needs to open new physical connections everytime which can cause exceptions(maximum default connection count is 100) but always will decrease the performance.
The best way to dispose/close connections(any
IDisposable) is by using theusingstatement:(sidenote: i’ve replaced your
DataSetwith a “lighter”DataTable)