Skip to content

Instantly share code, notes, and snippets.

@adilmughal
Created October 29, 2012 06:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adilmughal/3971868 to your computer and use it in GitHub Desktop.
Save adilmughal/3971868 to your computer and use it in GitHub Desktop.
A generic method to bind data source with several asp.net control
//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