Reputation: 1844
I have two lists of different types
List<Report>
List<Newsletter>
Is there a way to bind a gridview with both lists? Both classes are not implemented from a common interface.
I just need to display the name
and status
within the object properties. I mean, the type of the properties i want to bind is common to both list.
Upvotes: 0
Views: 3755
Reputation: 880
In such scenario I would use Linq-To-Objects to join between two collections and select only the properties I want to bind to GridView (resulting in anonymous collection). Then this anonymous collection can be used as data source of the GridView.
You can see great example on how L2O join can be done in this link
How to bind resulting data to GridView - you can see example in this article
Upvotes: 0
Reputation: 23113
Not directly, but you could create some kind of intermediate class:
public class ReporterNewsletterMixer
{
public Reporter Reporter { get; set; }
public Newsletter Newsletter { get; set; }
public string Name
{
get
{
if(Reporter == null)
return Newsletter.Name;
return Reporter.Name;
}
}
//same for status
public ReporterNewsletterMixer(Reporter reporter) { Reporter = reporter; }
public ReporterNewsletterMixer(Newsletter news) { Newsletter = news; }
}
Then you could mix the two lists together:
List<ReporterNewsletterMixer> mixed = new List<ReporterNewsletterMixer>();
reporters.Foreach(r => mixed.Add(new ReporterNewsletterMixer(r));
newsletter.Foreach(n => mixed.Add(new ReporterNewsletterMixer(n));
//bind to mixed
Upvotes: 0
Reputation: 15683
You can use Cast() method then union the lists
grv.DataSource = l1.Cast<object>().Union(l2.Cast<object>());
Upvotes: 0
Reputation: 31249
Maybe something like this:
ASPX
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="status" HeaderText="Status" />
</Columns>
</asp:GridView>
CS
gv.DataSource=reportList
.Select(x => new {x.Status,Name= x.text })
.Concat(
newsList
.Select(x => new {Status=x.Status.ToString(),Name= x.text }) );
gv.DataBind();
Upvotes: 1