Home > Back-end >  Is there a way to populate an ObservableCollection in Xamarin.Forms by reading a csv file?
Is there a way to populate an ObservableCollection in Xamarin.Forms by reading a csv file?

Time:11-18

I have a Student class below, and I am using an ObservableCollection in the ViewModel class to display students in a ListView. Is there I can read from a csv/spreadsheet to fill the ObservableCollection with students?

public class Student
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
    public string Module { get; set; }

    public Project(string Firstname, string Surname, string Module)
    {
        this.Firstname = Firstname;
        this.Surname = Surname;
        this.Module = Module;
}

public class ProjectListViewModel
{
    public ObservableCollection<Student> Students { get; set; }
    public ProjectListViewModel()
    {
        Students = new ObservableCollection<Project>();
        Students.Add(new Student("Ben", "Ledley", "Maths"));
        Students.Add(new Student("John", "Alex", "English"));
        Students.Add(new Student("Sam", "Craig", "Biology"));
}
        
}

CodePudding user response:

Yes,you could use CsvHelper to read the csv data by installing CsvHelper from NuGet Package.

You can create a .csv file and put it into Xamarin.Forms project. There is a similar example which reading a .csv file data.You can refer to the following code.

For example, the content of test.csv is as follows:(Set the Build Action as Embedded resource.):

ID,Name,Age
1,A,11
2,B,12
3,C,13
4,D,14
5,E,15

And the Item model is Item.cs

public  class Item
{
    public string ID { get; set; }

    public string Name { get; set; }

    public string Age { get; set; }
}

The MainPage.xaml

<StackLayout>
    <ListView  x:Name="mListView" HasUnevenRows="True">
        <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" HorizontalOptions="Fill" BackgroundColor="Olive">
                    <StackLayout Orientation="Vertical">
                        <Label Text = "{Binding Name}" FontSize="24" AbsoluteLayout.LayoutBounds="0.25, 0.25, 400, 40"/>
                        <Label Text = "{Binding Age}" AbsoluteLayout.LayoutBounds="50, 35, 200, 25"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Button Clicked="Button_Clicked" Text="Read data from CSV" />
</StackLayout>

The MainPage.xaml.cs

   public partial class MainPage : ContentPage
    {
        public ObservableCollection<Item> items { get; set; }
        public MainPage()
        {
            InitializeComponent();

            items = new ObservableCollection<Item>();

            mListView.ItemsSource = items;
        }

        private void Button_Clicked(object sender, EventArgs e)
        {

            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "ReadFromExcel.test.csv";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                //string result = reader.ReadToEnd();
                if (reader != null)
                {
                    using (var csv = new CsvReader(reader, CultureInfo.CurrentCulture))
                    {
                        while (csv.Read())
                        {
                            items.Add(new Item
                            {
                                ID = csv.GetField<string>(0),
                                Name = csv.GetField<string>(1),
                                Age = csv.GetField<string>(2)
                            });
                        }
                    }
                }

            }

        }
    }

Note: After clicking the Button ,we can read data from the .CSV file.

  • Related