Created
October 29, 2012 06:10
-
-
Save adilmughal/3971868 to your computer and use it in GitHub Desktop.
A generic method to bind data source with several asp.net control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Solution 1 | |
public void BindDataToControl<T>(BaseDataBoundControl control, IEnumerable<T> dataSource) | |
{ | |
if (control == null) | |
throw new ArgumentNullException("control"); | |
control.DataSource = dataSource; | |
control.DataBind(); | |
} | |
//other overloads | |
//Solution 2 | |
public void BindDataToControl<T>(Control control, IEnumerable<T> dataSource) | |
{ | |
if (control == null) | |
throw new ArgumentNullException("control"); | |
if (control.GetType() == typeof(DataGrid)) | |
((DataGrid)control).DataSource = dataSource; | |
else if (control.GetType() == typeof(Repeater)) | |
((Repeater)control).DataSource = dataSource; | |
else if (control.GetType() == typeof(DropDownList)) | |
((DropDownList)control).DataSource = dataSource; | |
else | |
return; // or throw exception | |
control.DataBind(); | |
} | |
//Solution 3 | |
public interface IBindableCustomControl | |
{ | |
void BindControl<T>(IEnumerable<T> dataSource); | |
} | |
public class CustomDataGrid : DataGrid, IBindableCustomControl | |
{ | |
public void BindControl<T>(IEnumerable<T> dataSource) | |
{ | |
this.DataSource = dataSource; | |
this.DataBind(); | |
} | |
} | |
//Some where else in code, kind of helper | |
public void BindDataToControl<T>(IBindableCustomControl control, IEnumerable<T> dataSource) | |
{ | |
if (control == null) | |
throw new ArgumentNullException("control"); | |
control.BindControl(dataSource); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment