2

I get this error:

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

My code:

protected void Button1_Click(object sender, EventArgs e)
{
        JobShopEntities job = new JobShopEntities();
        GridView1.DataSource = (from x in job.JobDescriptions where (x.Titlu == TextBox1.Text) select x).First();
        GridView1.DataBind();
}

I searched a lot for a solution.. From here I got this solution.

Rest of the code on back end in case have something to do with the error.

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 {
        GridViewRow row = GridView1.Rows[e.NewEditIndex];

        int rowId = Convert.ToInt32(row.Cells[1].Text);

        Response.Redirect("~/Administrator/Management/ManageJobs.aspx?id=" + rowId);
 }

1 Answer 1

1

You are bind the grid with object as First will give you an object instead of collection whereas the DataSource expect a collection. If you do not need to bind gridview with single record then you can remove the call of First method and call ToList() to get list of records.

If you need only the first record then you can use Enumerable.Take which will return you IEnumerable<TSource>

 GridView1.DataSource = (from x in job.JobDescriptions 
    where (x.Titlu == TextBox1.Text) select x).Take(1);

Edit as per comments by OP

If you are bind all the record then you should know know many record you have in the table. If record are in thousand then you can think about paging.

If record are in hundreds then you can use the same method using query without where clause in the Page_Load event.

if(!Page.IsPostBack)
{
     JobShopEntities job = new JobShopEntities();
     GridView1.DataSource = (from x in job.JobDescriptions).ToList();
     GridView1.DataBind();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hello thank you very much for fast response. I tried both ways but I get a error. Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
You probably have give DataSourceID in GridView tag like DataSourceID="Datasource1", and you are also give datasource in code behind. Remove DataSourceID from GridView tag as GridView can have on datasource at a time
Yea you are right... but I added a data source to my gridview to show all records and I want a search box above to search a record with a title.
Hello I forgot to respond yesterday. I modified a bit your code to work. In this ""from x in job.JobDescriptions"" I put select x in the end and instead of .Take(1); I put ToList(). But your solution was a great hint for me. Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.