VB.NET to C#: Using Data-Binding methods on object
-
25-10-2019 - |
سؤال
In VB.NET I created 2 shorthand functions for data binding gridviews/dropdownlists/etc from any datasource (such as a DataReader or IReader or collection, etc):
Public Shared Sub BindObject(ByVal objDataSource As Object, ByVal objItem As Object)
objItem.DataSource = objDataSource
objItem.DataBind()
End Sub
Public Shared Sub BindObject(ByVal objDataSource As Object, ByVal objItem As Object, ByVal sTextField As String, ByVal sValueField As String)
objItem.DataSource = objDataSource
If sTextField <> "" Then objItem.DataTextField = sTextField
If sValueField <> "" Then objItem.DataValueField = sValueField
objItem.DataBind()
End Sub
I converted this to C# as such:
public static void BindObject(object objDataSource, object objItem)
{
objItem.DataSource = objDataSource;
objItem.DataBind();
}
public static void BindObject(object objDataSource, object objItem, string sTextField, string sValueField)
{
objItem.DataSource = objDataSource;
if (!string.IsNullOrEmpty(sTextField))
objItem.DataTextField = sTextField;
if (!string.IsNullOrEmpty(sValueField))
objItem.DataValueField = sValueField;
objItem.DataBind();
}
Yet this obviously doesn't work as the Data-Binding methods aren't accessible to objItem, unless I explicity cast it to a type such as "ListBox" or "Gridview", etc. Similarly I want to retain the flexibility that objDataSource can be either an IReader, iCollection, etc.
Is it possible to replicate the VB.NET approach in C# using anonymous methods or something similar?
Thanks.
المحلول
You could use the "var" anonymous type or enter a case statement to see what type your incoming object is.
-edit-
You are correct, the var does not seem workable here. Please try this solution instead:
public void BindObject(object objDataSource, object objItem)
{
(objItem as BaseDataBoundControl).DataSource = objDataSource;
(objItem as BaseDataBoundControl).DataBind();
}
Regards, Paul
نصائح أخرى
You've got Option Strict turned off in your VB code. Tsk tsk — that's not really the best choice.
To get a similar effect in C#, you can do this:
public static void BindObject(object objDataSource, dynamic objItem)
{
objItem.DataSource = objDataSource;
objItem.DataBind();
}
public static void BindObject(object objDataSource, dynamic objItem, string sTextField, string sValueField)
{
objItem.DataSource = objDataSource;
if (!string.IsNullOrEmpty(sTextField))
objItem.DataTextField = sTextField;
if (!string.IsNullOrEmpty(sValueField))
objItem.DataValueField = sValueField;
objItem.DataBind();
}
But again, you should really look into a way to do this that preserves strong compile-time type checking.