C# Repeater.DataSource from 2 StringCollections
-
21-08-2019 - |
Question
I have 2 StringCollections:
StringCollection ParameterIDs
StringCollection ParameterValues
Is it able to map these both StringCollections as DataSource, something like:
repeater.DataSource = ParameterIDs (as row1) + ParameterValues (as row2);
repeater.DataBind();
and use them in repeater like:
<asp:Repeater ID="repeatParameters" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td class="formLabel">
<asp:Label ID="lblParameterID" Text="<% #DataBinder.Eval(Container.DataItem,"ParameterIDs") %>" runat="server" MaxLength="50"></asp:Label><br />
</td>
<td class="formInputText">
<asp:Label ID="lblParameterValue" Text="<%#DataBinder.Eval(Container.DataItem,"ParameterValues") %>" runat="server" MaxLength="50"></asp:Label><br />
</td>
</tr>
<tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Solution
This will do exactly what you want, providing you are using .NET 3.5:
StringCollection parameterIds = new StringCollection();
StringCollection parameterValues = new StringCollection();
parameterIds.Add("someID");
parameterValues.Add("someValue");
var dataSource = parameterIds.Cast<string>()
.SelectMany(itemOne => parameterValues
.Cast<string>(), (itemOne, item2) => new { Row1 = itemOne, Row2 = item2 });
repeater.DataSource = dataSource;
repeater.DataBind();
Like Bogdan_Ch has said, I recommend you move away from StringCollection
to List<string>
if you are using .NET 2.0 and above. Doing that has the added advantage that you don't need to use the Cast
extension method.
OTHER TIPS
First thought:
Mash them up in a Dictionary and use that as a datasource.
Second thought:
Create a DataSet with the values you need.
Third thought:
Use KeyValuePair.
As you see there are a lot of different ways of doing this but all of them share a common element:
Create a single object which stores and maps the corresponding values.
No, because the DataSource requires an object with the ICollection interface.
Like the others said, you could create a dictionary or something like:
List<KeyValuePair<string,string>>
Where the parameter id is the key, and the parameter value is the value in the KeyValuePair.
I would populate a Dictionary with your string collections and then bind to the Dictionary.
I would suggest 2 options 1. In .NET 1.1 you don't have generic lists, so you may join collections manually in your code, and then use joined collectionas a datasource
StringCollection joined = new StringCollection();
foreach(string s in stringCollection1)
joined.Add(s);
foreach (string s in stringCollection2)
{
if (!joined.Contains(s))
joined.Add(s);
}
In .NET 2.0 and more I would suggest you to use List instead of StringCollection With AddRange() you can add another list to an existing list.
In .NET 3.5 you can use Linq to intersect 2 lists
public static IEnumerable<TSource> Intersect<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second
)