04 January 2008

DataAdapter and database connections

I didn't know this until a few minutes ago: DataAdaptors manage the opening and closing of the database connection for you.

More specifically, if the connection is not already open, the DataAdaptor will open it and then close it when it is done. If it is already open, the DataAdaptor will leave it open when it's done. Very clever I think.

So, the only time when you'd want to manually open and close the connection is when you want to perform several tasks in a row, all using the same connection.

Raising events from user controls (.ascx)

Just like the DropDownList control has a SelectedIndexChanged event, you can create custom events for your custom user controls.

In the user control...

Public Event MyEvent As System.EventHandler

Protected Sub DoSomething()
    RaiseEvent MyEvent(Me, New EventArgs())
End Sub

And in the main page which contains the user control...

Protected Sub myControl_MyEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles myControl.MyEvent
    'Code goes here
End Sub

Quite good really. Now I just need to figure out how to cause a postback from the user control!

03 January 2008

Casting an array

It looks like there is no built in method for converting an array from one type to another. This DOES NOT work...

Dim arInt As Integer() = {1, 2, 3}
Dim arString As String() = arInt

The only solution seems to be to loop through the original array and insert the elements into a new array one at a time. Seems silly to me.

Don't use DataReader with ObjectDataSource

I develop a lot of database heavy web apps, and sometimes my business layer returns DataReader objects. Like a good little coder I always use CommandBehavior.CloseConnection, like this...

Return ExecuteReader(CommandBehavior.CloseConnection)

I assumed if I passed this to an ObjectDataSource, then .Net would take care of closing the database connection for me, but this is not the case. Even though I've specified the command behavior, it just leaves the connection open.

The best solution seems to be return a DataSet or DataTable, which means that you can manually close the database connection before passing the object to the ObjectDataSource.