Adding Parameters to the Generic BindListControl Method
25 03 2008Yesterday, I blogged about a generic method I created that could take a series of parameters and bind most any type of IEnumerable data source to most any type of DataBoundControl control. I needed a simple and portable method (so that I could eventually toss it into the base helper library I use).
Unfortunately, the post didn’t cover something quite common—what happens when your data methods have parameters? Integers, strings, even objects (passing a User object, etc).
For this, I’ll be modifying our “third attempt,” which, for now is, is the final version of the code. Here’s the change.
protected void BindDataControl
<TDataControlType, TEnumerableType, TDataSourceClass>
(bool hasBeenModified, string sessionVariable,
TDataControlType dataControl,
string dataSourceMethod,
TDataSourceClass dataSourceClass,
object[] methodArguments)
where TDataControlType : DataBoundControl,
new() where TEnumerableType : IEnumerable,
new() where TDataSourceClass : class
{
// If session is null or has been modified
// (thus invalidated), update the session state.
if (Session[sessionVariable] == null || hasBeenModified)
{
// Invoke the specified method that
//creates our data source.
var data = dataSourceClass.GetType().InvokeMember(
dataSourceMethod,
BindingFlags.InvokeMethod |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance,
null,
dataSourceClass, methodArguments);
// Add it to session.
Session.Add(sessionVariable, data);
}
// Read the data from session and bind the data control.
dataControl.DataSource =
(TEnumerableType)Session[sessionVariable];
dataControl.DataBind();
}
Pay close attention to the new methodArguments object array. I’ve bolded them in the code above. The InvokeMember reflection method allows for arguments to be passed, so I simply opened that up to the calling method.
To use this, here’s an example that takes the Page.User property and passes it to a LINQ data context method:
BindDataControl<ListView, List<Gallery>, WebGalleryDataContext>
(true,
“GalleryList”,
GalleriesList,
“GetGalleriesByRole”,
db,
new [] { Page.User });
or, pulling from the QueryString:
BindDataControl<ListView, List<WebFile>, WebGalleryDataContext>
(true,
“CurrentGallery”,
lv,
“GetWebFilesByGalleryName”,
db,
new [] {Request.QueryString["id"]});
and passing multiple arguments with different base types:
BindDataControl
<ListView, List<IGrouping<Gallery, WebFile>>,
WebGalleryDataContext>
(true,
“ChangesSinceLastVisit”,
listViewTest,
“GetAllSinceLastVisit”,
db,
new object[]
{Convert.ToDateTime(Session["LastLoginDate"]),
Page.User});
Cool.




