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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11754104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:06:21  来源:igfitidea点击:

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

c#gridview

提问by user1566490

Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource. The error is displayed when I bind the grid view

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

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

i have the query

我有疑问

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

回答by Yograj Gupta

You are returning a single object from GetEmployeebyName method and binding that to the GridViewEmployee, thats why it is giving error.

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

You can change it like

你可以改变它像

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 must be a type of collection as the exception is stating ( It must be either an IListSource, IEnumerable, or IDataSource)

DataSource 必须是一种集合类型,因为异常声明(它必须是 IListSource、IEnumerable 或 IDataSource)

回答by uk2k05

Could the above not be shortend to..

以上不可以简写为..

var empInfo = dal.GetEmployeebyName(name);

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

回答by FunMatters

In my testing page I make us of the following piece of code to display a list of different objects or just a single object in the same gridview.

在我的测试页面中,我让我们使用以下代码段来显示不同对象的列表或在同一个 gridview 中仅显示单个对象。

   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();

Hope it helps! It works for me :)

希望能帮助到你!这个对我有用 :)