Connecting an ObjectDataSource to a DataTable in Code-behind
After Googling for quite a while, I never managed to find a good step-by-step or MSDN article on creating ObjectDataSources programmatically and then linking them to DataTables, GridViews, etc. So, after disecting the UI-layer code, here’s what I came up with.
When placing a server-side control on an ASPX page, your code looks similar to:
<asp:ObjectDataSource ID=”odsLookupItemList” runat=”server”
Name=”firstName” PropertyName=”Text” Type=”String” />
Name=”lastName” PropertyName=”Text” Type=”String” />
That’s fine and dandy; however, sometimes you don’t want the ODS to fire off on Page_Load, but after an event has occured on the page, such as, in this case, searching for an Item object by first or last name.
ObjectDataSource odsLookupItemList = new ObjectDataSource();
odsLookupItemList.SelectMethod = “GetItemCollectionByFirstOrLastName”;
odsLookupItemList.TypeName = “Framework.Collections”;
odsLookupItemList.SelectParameters.Add(“firstName”, TypeCode.String, txtFirstName.Text);
odsLookupItemList.SelectParameters.Add(“lastName”, TypeCode.String, txtLastName.Text);
DataTable dt = (DataTable)odsLookupItemList.Select();
You can also shortcut, when creating the ODS object, to save a few lines of code, by placing the TypeName and Select Method into an overloaded constructor:
ObjectDataSource ods = new ObjectDataSource(“Framework.Collections”, “GetItemCollectionByFirstOrLastName”);
This requires your ODS to return a result that is either convertable to the object you are trying to place it in (such as a DataTable) or, even better, placing it back in it’s original object type (without casting) and iterating through as necessary for your application.
Now, rather than firing off (and, if the SelectParameters are null, producing nothing), the actual ObjectDataSource isn’t even created until it’s necessary and it’s event, such as a Button’s Click event, has occured.