Andrew Vassallo
Andrew Vassallo

Reputation: 33

Using a While Loop to Populate Custom ListView in Xamarin Forms

I'm still very new to programing, and after a day of banging my head against the wall I'm asking for help.

I've been messing with listviews lately in Xamarin Forms and now I'm trying to use a while loop to generate all of my rows.

What I really want to do it use a while loop, or something, to populate the area within the curly brackets"{ }" of the below snippet of code

 TransactionsList.ItemsSource = new List<Contacts>() {  };

They way it's setup right now when ever I add

new Contacts() { ListAmount = TransactionsAmounts[i], ListDescription = TransactionsDescriptions[i], } 

inside the brackets I'm able to create a new row in the listview. This is great, but now I want to do it in a way that lets me populate it with my arrays without having to write out each line to create a row. I want my arrays to dictate the size of the list. (arrays will always be the same size)

Is there an easier way of doing this? Or is there a way to use a use a loop, or something, to populate the area in the curly brackets?

Hope that makes sense. I'm not very good at describing things like this. If you need anymore info, or anything, just let me know.

Below is the listview xaml

<ListView x:Name="TransactionsList" HasUnevenRows="True">
        <ListView.ItemTemplate >
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <StackLayout Orientation="Vertical">
                            <Label Text="{Binding ListAmount}" Font="18"></Label>
                            <Label Text="{Binding ListDescription}" TextColor="Gray"></Label>
                        </StackLayout>
                      <!--  <Label Text="{Binding ListDates}" TextColor="Blue" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End"></Label> -->
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Upvotes: 3

Views: 3009

Answers (1)

Jason
Jason

Reputation: 89082

var contacts = new List<Contacts>();

for (int ndx = 0; ndx < trasactionCount; ndx++) {
  contacts.Add(new Contacts { ListAmount = TransactionsAmounts[ndx], ListDescription = TransactionsDescriptions[ndx] });
}

TransactionsList.ItemsSource = contacts;

Upvotes: 3

Related Questions