user919789
user919789

Reputation: 171

How to copy an ASP .NET listview which contains data from a DB?

I'm currently working on a Web Application which queries ONE database table multiple times with different constraints. I'm making use of ASP .NET 3.5 ListView. I have about 10 different listviews. Is there a way where I could just query the table one time as a whole, and then segregate them into separate tables into the ASP .NET Listviews??

Is there a way to utilize one query and output to multiple ASP .NET listviews? Or is there a way to use 1 SQL Data Source, and use it with 2 Listviews?

If this is not possible, am I able to copy an ASP .NET Listview to another ASP .NET listview? I've tried this code but I get an error:

         private void CopySelectedItems(ListView source, ListView target)
        {
           foreach (ListViewItem item in source.SelectedItems)
           {
               target.Items.Add((ListViewItem)item.Clone());
           }
        } 

The errors are:

Error 1 'System.Web.UI.WebControls.ListView' does not contain a definition for 'SelectedItems' and no extension method 'SelectedItems' accepting a first argument of type 'System.Web.UI.WebControls.ListView' could be found (are you missing a using directive or an assembly reference?)

Error 2 'System.Web.UI.WebControls.ListViewItem' does not contain a definition for 'Clone' and no extension method 'Clone' accepting a first argument of type 'System.Web.UI.WebControls.ListViewItem' could be found (are you missing a using directive or an assembly reference?

Error 3 The best overloaded method match for 'System.Collections.Generic.ICollection.Add(System.Web.UI.WebControls.ListViewDataItem)' has some invalid arguments

Error 4 Argument '1': cannot convert from 'System.Web.UI.WebControls.ListViewItem' to 'System.Web.UI.WebControls.ListViewDataItem'

Upvotes: 1

Views: 1318

Answers (1)

Mike Guthrie
Mike Guthrie

Reputation: 4059

You can load your single database query into a list, then use the Where extension method on the list to bind to your individual ListView controls.

For example, assuming data is loaded into class MyDataClass which has a string property MyProperty1:

List<MyDataClass> myList = MyDataAccessLayer.GetFromDatabase();

ListView1.DataSource = myList.Where(item => item.MyProperty1 == "value1");
ListView1.DataBind();
...
ListView10.DataSource = myList.Where(item => item.MyProperty1 == "value10");
ListView10.DataBind();

Upvotes: 2

Related Questions