简体   繁体   中英

Convert a class object to a DataSource

Say I have a simple class:

public class Employee
{
     public string firstName { get; set; }
     public string lastName { get; set; }
}


Employee emp = new Employee();
emp.firstName = "joe";
emp.lastName = "smith";

What I'm looking for is a way to easily map these values to a web control, for example a DataGrid .

datagrid1.DataSource = emp;

If I try straight out I get an error:

Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.

Any suggestions regarding the best way to achieve this appreciated.

As the error clearly saying the DataSource expects an IListSource , IEnumerable , or IDataSource but you are sending a one instance of the Employee . You can use a List with only one item like this:

datagrid1.DataSource = new List<Employee> {emp};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM