简体   繁体   中英

Reading CSV file in C# WPF

I have this application that I am creating to get some more practise in C# and reading and writing to a CSV file. I would like to display some different animals from a CSV file into a datagrid in WPF. I have been successful in using the exact same code in one part of my application to display animal categories from a different CSV file but could anyone see why this wouldnt be displaying animals. I have changed my code around to the different CSV location and added in the different columns I would like to display but I cannot figure out why this wont work.

Below is the code that I have for my datagrid section to display the animals.

private void DataGridViewAnimals_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Animal animal= new Animal();
            string[] AnimalArray;

            DataTable dt = new DataTable();
            dt.Columns.Add("Animal", typeof(string));

            using (StreamReader reader = new StreamReader(@"C:\Users\ashle\OneDrive\Documents\Uni\Level 5\Object Orientated Programming\Practical\CSV Files\animal.csv"))
            {
                while (!reader.EndOfStream)
                {
                    AnimalArray = reader.ReadLine().Split(',');

                    animal.Type = AnimalArray[0];
                    animal.Category = AnimalArray[1];
                    animal.Colour = AnimalArray[2];
                    animal.Origin = AnimalArray[3];

                    dt.Rows.Add(AnimalArray);
                }
                DataView dv = new DataView(dt);
                DataGridViewAnimals.ItemsSource = dv;
            }
        }

Sorry I am very new to C# and WPF so could anyone see if there are any issues. I have tried searching for different ways to do it but I have had no luck. If you need any more information please ask:) thank you

Edit: This is my code for the DataGrid that is pulling through the data from my CSV file

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AnimalCategory animalCategory = new AnimalCategory();
            string[] CategoryArray;

            DataTable dt = new DataTable();
            dt.Columns.Add("Animal Category", typeof(string));

            using (StreamReader reader = new StreamReader(@"C:\Users\ashle\OneDrive\Documents\Uni\Level 5\Object Orientated Programming\Practical\CSV Files\animalcategory.csv"))
            {
                while (!reader.EndOfStream)
                {
                    CategoryArray = reader.ReadLine().Split(',');

                    animalCategory.Category = CategoryArray[0];

                    dt.Rows.Add(CategoryArray);
                }
                DataView dv = new DataView(dt);
                DataGridViewAnimalCategories.ItemsSource = dv;
            }
        }

And below shows the markup for my XAML UI for the first piece of code that is not working.

<Window x:Class="AnimalWatchersUnited2.Animals"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AnimalWatchersUnited2"
        mc:Ignorable="d"
        Title="Animals" Height="450" Width="800" >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="1.1*"/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Rectangle Fill="LightPink" Grid.Row="0" Grid.ColumnSpan="6"/>
        <Label Content="Animal Watchers United" FontSize="36" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.ColumnSpan="6" FontFamily="Candara" />
        <Button Click="ClickMainMenu" Content="Main Menu" Grid.Column="0" Grid.Row="1" Height="50px" Width="110px" Margin="10,0,12,50"/>
        <Button Click="ClickAnimalCategories" Content="Animal Categories" Grid.Column="1" Grid.Row="1" Height="50px" Width="110px" Margin="10,0,12,50"/>
        <Button Content="Animals" Grid.Column="2" Grid.Row="1" Height="50px" Width="110px" Margin="12,0,10,50"/>
        <Button Content="Sightings" Grid.Column="3" Grid.Row="1" Height="50px" Width="110px" Margin="12,0,10,50"/>
        <Button Content="Wishlist" Grid.Column="4" Grid.Row="1" Height="50px" Width="110px" Margin="12,0,10,50"/>
        <Button Click="ClickLogout" Content="Logout" Grid.Column="5" Grid.Row="1" Height="50px" Width="110px" Margin="10,0,10,50"/>


        <DataGrid Name="DataGridViewAnimals" Grid.Column="1" Grid.Row="2" RenderTransformOrigin="0.808,0.668" Grid.ColumnSpan="3" Grid.RowSpan="2" SelectionChanged="DataGridViewAnimals_SelectionChanged"/>
    </Grid>
</Window>

The issue is that you're adding an array of strings to a grid with only one column. It won't have space to add 4 items per animal when you only have 1 column. If I am correct, you should be getting an inner exception that says "Input array is longer than the number of columns in this table."

Try defining more columns for the values to go into like this:

string[] AnimalArray;

DataTable dt = new DataTable();
dt.Columns.Add("Type", typeof(string));
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Colour", typeof(string));
dt.Columns.Add("Origin", typeof(string));

using (StreamReader reader = new StreamReader(@"C:\Users\ashle\OneDrive\Documents\Uni\Level 5\Object Orientated Programming\Practical\CSV Files\animal.csv"))
{
    while (!reader.EndOfStream)
    {
        AnimalArray = reader.ReadLine().Split(',');

        dt.Rows.Add(AnimalArray);
    }
    DataView dv = new DataView(dt);
    DataGridViewAnimals.ItemsSource = dv;
}

If this still doesn't work, please show us the code for the one that does work along with the xaml markup for the UI.

Edit: As pointed out by Fildor, you are not using the animal variable this way, so there's no point in setting its properties, unless you want to use the data somewhere else.

Edit 2: The second problem lies in the event itself. The code for the one that WORKS is in the method Window Loaded which will be called when the window gets loaded I presume. That's why it works.

SelectionChanged on the other hand, gets called when an item in the grid is selected. Since there is no data in the grid yet, no item can be selected in the first place in order to call the method.

In other words, the location of the code is incorrect. Simply remove the SelectionChanged event handler from the DataGrid in the UI, and add a click method for one of the buttons (I'm guessing the Animals button), and put the code in there instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM