c# - 将类对象转换为数据源

标签 c# asp.net

假设我有一个简单的类(class):

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


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

我正在寻找一种将这些值轻松映射到 Web 控件(例如 DataGrid)的方法。

datagrid1.DataSource = emp;

如果我直接尝试,则会收到错误:

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

任何有关实现这一目标的最佳方法的建议表示赞赏。

最佳答案

由于错误明确指出 DataSource 需要 IListSourceIEnumerableIDataSource,但您正在发送Employee 的一个实例。您可以使用 List只有这样的一项:

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

关于c# - 将类对象转换为数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47056829/

相关文章:

c# - 错误 : No mapping exists from object type

c# - 拖放数据网格

asp.net - 什么是用于安全目的的验证码?

c# - 限制用户上传大文件

asp.net - 读取和编辑 Web.config 中的配置

c# - 如何使用 linq 树表达式创建具有动态列的数据透视表

c# - 如何将 WebResponse.GetResponseStream 返回值转换成字符串?

c# - 从 base64 检查文件类型?

c# - 将 tabitem 转换为窗口

c# - ApiController int 或 string URI 参数的相同路由