Articles in this section
Category / Section

How to bind data from the DataTable to ListView in Xamarin.Forms?

1 min read

ListView allows you to bind the data directly from the DataTable by converting the data table rows in to the collection and bind it to the ItemsSource property but the data model values is in array type, so you can directly bind the array values in the element.

xaml

<ContentPage xmlns:syncfusion="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms">
    <syncfusion:SfListView x:Name="listView"
                           ItemsSource="{Binding ContactsInfo}"
                           ItemSize="70" >
        <syncfusion:SfListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <Grid>
                            <Label LineBreakMode="NoWrap"
                                   TextColor="#474747"
                                   Text="{Binding ItemArray[0]}"/>
                            <Label LineBreakMode="NoWrap"
                                   TextColor="#474747"
                                   Text="{Binding ItemArray[1]}"/>
                            <Label LineBreakMode="NoWrap"
                                   TextColor="#474747"
                                   Text="{Binding ItemArray[2]}"/>
                            <Label LineBreakMode="NoWrap"
                                   TextColor="#474747"
                                   Text="{Binding ItemArray[3]}"/>
                        </Grid>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </syncfusion:SfListView.ItemTemplate>
    </syncfusion:SfListView>
</ContentPage>  

 

C#

 
public class ListViewGroupingViewModel
{
    private ObservableCollection<object> contactsInfo;
    public DataTable dt;
 
    public ListViewGroupingViewModel()
    {
        GenerateSource(100);
    }
 
    public void GenerateSource(int count)
    {
        contactsInfo = new ObservableCollection<object>();
 
        dt = new DataTable("Student");
        dt.Columns.Add("ContactID", typeof(Int32));
        dt.Columns.Add("ContactName", typeof(string));
        dt.Columns.Add("ContactType", typeof(string));
        dt.Columns.Add("ContactNumber", typeof(string));
 
        //Data  
        for (int i = 0; i < count; i++)
        {
            dt.Rows.Add(i, CustomerNames[i], contactType[random.Next(0, 5)], random.Next(100, 400).ToString() + "-" + random.Next(500, 800).ToString() + "-" + random.Next(1000, 2000).ToString());
        }
 
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            contactsInfo.Add(dt.Rows[i]);
        }
    }
}

 

Click here to download the sample.

 

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied