user1566490
user1566490

Reputation: 75

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

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

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

Upvotes: 3

Views: 39127

Answers (3)

FunMatters
FunMatters

Reputation: 601

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.

   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 :)

Upvotes: 1

uk2k05
uk2k05

Reputation: 388

Could the above not be shortend to..

var empInfo = dal.GetEmployeebyName(name);

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

Upvotes: 1

Yograj Gupta
Yograj Gupta

Reputation: 9869

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

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)

Upvotes: 5

Related Questions