数据源是无效类型。它必须是IListSource,IEnumerable或IDataSource

时间:2012-08-01 07:00:30

标签: c# gridview

数据源是无效类型。它必须是IListSource,IEnumerable或IDataSource。绑定网格视图时显示错误

var list = dal.GetEmployeebyName(name);
GridViewEmployee.DataSource = list;
GridViewEmployee.DataBind();

我有查询

public EmployeeInfo GetEmployeebyName(String name)
{
    using (var context = new HRMSEntities())
    {
        return context.EmployeeInfo.FirstOrDefault(e => e.FName == name);
    }
}

3 个答案:

答案 0 :(得分:5)

您正在从GetEmployeebyName方法返回单个对象并将其绑定到GridViewEmployee,这就是它给出错误的原因。

您可以像

一样进行更改
var empInfo = dal.GetEmployeebyName(name);
var list = new List<EmployeeInfo>{empInfo};

//or you can do this 
//var list = new List<EmployeeInfo>();
//list.Add(empInfo);

GridViewEmployee.DataSource = list;
GridViewEmployee.DataBind();

DataSource必须是一种集合,因为异常是在说明(它必须是IListSource,IEnumerable或IDataSource)

答案 1 :(得分:1)

以上不能缩短为......

var empInfo = dal.GetEmployeebyName(name);

GridViewEmployee.DataSource = empInfo.ToList();
GridViewEmployee.DataBind();

答案 2 :(得分:1)

在我的测试页面中,我使用以下代码来显示不同对象的列表或同一网格视图中的单个对象。

   var data = bl.getAirlines();
   // If single object returned cast to List
   // Note that could be already a list of 1 item though!
    if (data.Count == 1)
    {
        var list = new List<object> { data };               
        GridView1.DataSource = list;
    }
    else
     // Bind to list of items returned
        GridView1.DataSource = data;

    GridView1.DataBind();

希望它有所帮助!它对我有用:)