Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need generic utility C# method for populating ASP.NET DropDownList

Tags:

c#

asp.net

I have a method like the following in a utility class. I would like to change the parameter dataSource to accept any type of data source, that is, DataSet, DataView, List<T>, DataTable, and ArrayList.

Is this possible? How would I change the method signature (and parameters and types) to allow me the flexibility of passing in any acceptable datasource for binding?

public void FillCombo(DropDownList ddl, DataTable dataSource, string textField, string valueField, bool addSelect) {
    ddl.DataValueField = valueField;
    ddl.DataTextField = textField;
    ddl.DataSource = dataSource;
    ddl.DataBind();
    if (addSelect) 
        AddSelectCombo(ddl, "Select", -1);
}
like image 314
David Avatar asked Dec 22 '22 07:12

David


2 Answers

Well, since the DataSource property on a DropDownList has type object you could change your method signature to accept an object. That would not make your method generic (in the .NET sense), but maybe it would be enough anyway.

like image 117
Klaus Byskov Pedersen Avatar answered Dec 24 '22 21:12

Klaus Byskov Pedersen


I believe the following is what you're looking for.

public void FillCombo<TSource>(DropDownList ddl, TSource dataSource, string textField, string valueField, bool addSelect) {

    ddl.DataValueField = valueField;
    ddl.DataTextField = textField;
    ddl.DataSource = dataSource;
    ddl.DataBind();

    if (addSelect) AddSelectCombo(ddl, "Select", -1);

}
like image 37
Adam Maras Avatar answered Dec 24 '22 20:12

Adam Maras