user3432257
user3432257

Reputation: 415

"Data source is an invalid type" exception when binding a single row to a listview

I have grid view to show all customers names, and when a user click on any name, I use a listview to show that information of the selected customer.

So, in the past, if I have more than one customer in the page, I will have a grid view fill, and the listview is empty until the user selects any customer.

this is the code:

var results = MyClass.GetCustomerInformation(CallerId);
rowCount = results.Rows.Count;
CallerId = rowCount > 0 ? results.Rows[0][4].ToString() : CallerId;
if (rowCount > 1)
{
    ListView1.Enabled = false;
    GridView1.DataSource = results;
    GridView1.DataBind();
}
else
{
    GridView1.Enabled = false;
    ListView1.DataSource = results;
    ListView1.DataBind();
}

Now

I need the listview to have the first customer when there are more than one customer.

So, I edited my code to this code:

var results = MyClass.GetCustomerInformation(CallerId);
rowCount = results.Rows.Count;
CallerId = rowCount > 0 ? results.Rows[0][4].ToString() : CallerId;
if (rowCount > 1)
{
    //new
    ListView1.DataSource = results.Rows[0];
    ListView1.DataBind();
    //new
    GridView1.DataSource = results;
    GridView1.DataBind();
}
else
{
    GridView1.Enabled = false;
    ListView1.DataSource = results;
    ListView1.DataBind();
}

But I got this exception:

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

Note

The function GetCustomerInformation returns DataTable type

Upvotes: 0

Views: 562

Answers (1)

John Saunders
John Saunders

Reputation: 161773

When you set the data source to a single row, you caused your problem.

The DataRow type does not implement IListSource, IEnumerable, or IDataSource. You need to pass one of those to the DataSource property, but you passed DataRow instead.

The thing to do is to create an IEnumerable<DataRow> from your single DataRow. Try this:

ListView1.DataSource = new DataRow[]{results.Rows[0]};

This creates an array of DataRow which contains only your first row. DataRow[] implements IEnumerable<DataRow>, so it works.

Upvotes: 1

Related Questions