简体   繁体   English

读取CSV文件在C# WPF

[英]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.我正在创建这个应用程序,以便在 C# 中进行更多练习,并读写 CSV 文件。 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.我想将 CSV 文件中的一些不同动物显示到 WPF 中的数据网格中。我已经成功地在我的应用程序的一部分中使用完全相同的代码来显示来自不同 CSV 文件的动物类别,但是任何人都可以看到为什么这不会展示动物。 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.我已将我的代码更改为不同的 CSV 位置,并添加到我想显示的不同列中,但我无法弄清楚为什么这不起作用。

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.抱歉,我是 C# 和 WPF 的新手,所以任何人都可以看看是否有任何问题。 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编辑:这是我的 DataGrid 代码,它从我的 CSV 文件中提取数据

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.下面显示了我的 XAML UI 的第一段无效代码的标记。

<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.当您只有 1 列时,它没有空间为每只动物添加 4 个项目。 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:尝试为 go 的值定义更多列,如下所示:

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.如果这仍然不起作用,请向我们展示能与 xaml 标记一起工作的 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.编辑:正如 Fildor 所指出的,您没有以这种方式使用动物变量,因此设置其属性没有意义,除非您想在其他地方使用数据。

Edit 2: The second problem lies in the event itself.编辑2:第二个问题在于事件本身。 The code for the one that WORKS is in the method Window Loaded which will be called when the window gets loaded I presume. WORKS 的代码在方法 Window Loaded 中,我认为当加载 window 时将调用该方法。 That's why it works.这就是它起作用的原因。

SelectionChanged on the other hand, gets called when an item in the grid is selected.另一方面,SelectionChanged 在选择网格中的项目时被调用。 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.只需从 UI 中的 DataGrid 中删除 SelectionChanged 事件处理程序,并为其中一个按钮(我猜是 Animals 按钮)添加一个点击方法,然后将代码放在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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