【问题标题】:C# WPF Read/Edit CSVC# WPF 读取/编辑 CSV
【发布时间】:2017-09-05 20:27:30
【问题描述】:

我目前正在用 WPF C# 编写一个应用程序,它是用 Java 编写的其他进程的某种帮助程序。这些其他进程需要一个 configuration.csv,其中列出了不同的“名称”,并带有一个“SKIP”列。如果在 Skip 列是 X,我的 java 程序将跳过这些名称,因此它们的依赖进程。

如果我用 Excel 打开 CSV 并编辑行,一切正常。那不是问题。我想要实现的是将行列出到 WPF 应用程序中的 DataGrid 中(第一行和最后一行除外),用户可以在其中勾选复选框以决定是否要跳过该特定名称。按保存,.CSV 得到更新。

我已经和一个更熟悉这个主题的朋友一起写了一些代码。它在 WinForms 中运行良好,但在 WPF 上不起作用。我们无法获取复选框的值,也无法将它们保存到 CSV。

代码:

    private void OBJ_SaveButton_Click(object sender, RoutedEventArgs e)
    {
        if (OBJ_DataGrid.Items.Count == 0)
        {
            MessageBox.Show("Kein Datensatz in der View.");
            return;
        }
        /*if (Directory.Exists(path))
        {
            if (File.Exists(filepath))
            {
                string tmp = null;
                try
                {
                    FileStream fileStr = new FileStream(filepath, FileMode.Create);
                    StreamWriter strWriter = new StreamWriter(fileStr);
                    strWriter.WriteLine("SFObject;Skip");
                    for(int i=0;i< itmGrd.Count;i++)
                    {
                        switch (itmGrd[i].ItemValue)
                        {
                            case true:
                                tmp = itmGrd[i].ItemName + ";X";
                                break;
                            case false:
                                tmp = itmGrd[i].ItemName + ";";
                                break;
                        }
                        strWriter.WriteLine(tmp);
                    }
                    strWriter.WriteLine("SuccessMSG;");
                    strWriter.Close();
                    fileStr.Close();
                    LoadConf();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
                MessageBox.Show("ERR_F0: Pfad nicht gefunden.");
        }
        else
            MessageBox.Show("ERR_D0: Pfad nicht gefunden.");*/
    }

    private void OBJ_ReloadButton_Click(object sender, RoutedEventArgs e)
    {

    }

    private void OBJ_DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }

    private void OBJ_DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        MessageBox.Show(e.Row.ToString());
    }

    void OnChecked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(e.Source.ToString());
    }


}

public class ItemGrid
{
    public ItemGrid(string name, bool rval)
    {
        ItemName = name;
        ItemValue = rval;
    }

    public string ItemName { set; get; }
    public bool ItemValue { set; get; }
}

public class ItemsGrid : List<ItemGrid>
{
    public string path = null;
    public string filepath = null;
    public ItemsGrid()
    {
        path = String.Format(@"{0}\build\", Environment.CurrentDirectory);
        filepath = Path.Combine(path + "configuration.csv");
        if (Directory.Exists(path))
        {
            if (File.Exists(filepath))
            {
                string line = null;
                StreamReader file = new StreamReader(filepath);
                while ((line = file.ReadLine()) != null)
                {
                    if (!line.Equals("SFObject;Skip") && !line.Equals("SuccessMSG;"))
                    {
                        string input = (line.IndexOf(";X") != -1 ? (line.Replace(";X", "")) : (line.Replace(";", "")));
                        Add(new ItemGrid(input, (line.IndexOf(";X") != -1 ? (true) : (false))));
                    }
                }
                file.Close();
            }
            else
                MessageBox.Show("ERR_F0: Pfad nicht gefunden.");
        }
        else
            MessageBox.Show("ERR_D0: Pfad nicht gefunden.");


        //Add(new ItemGrid("Tom", false));
        // Add(new ItemGrid("Jen", false));

    }

}

这就是它的外观(并且应该看起来像)。

CSV:

我希望你们能帮助我,我真的不明白为什么它不起作用。我也不得不承认,我还没有精通 C#。

【问题讨论】:

    标签: c# wpf visual-studio csv xaml


    【解决方案1】:

    我假设您粘贴的 CSV 格式正确。

    // HelperClass.cs
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WpfCsvSkipTicker
    {
        public static class HelperClass
        {
            public static  List<ItemGrid> ReadCsv(string filepath)
            {
                if (!File.Exists(filepath)) return null;
                var allLines = File.ReadAllLines(filepath);
                var result =
                    from line in allLines.Skip(1).Take(allLines.Length -2)
                    let temparry = line.Split(';')
                    let isSkip =
                        temparry.Length > 1
                        && temparry[1] != null
                        && temparry[1] == "X"
                    select new ItemGrid { ItemName = temparry[0], ItemValue = !isSkip };
                return result.ToList();
            }
    
            public static void WriteCsv(IEnumerable<ItemGrid> items, string filepath)
            {
                var temparray = items.Select(item => item.ItemName + ";" + (item.ItemValue ? "" : "X")).ToArray();
                var contents = new string[temparray.Length + 2];
                Array.Copy(temparray, 0, contents, 1, temparray.Length);
                contents[0] = "SFOBject;Skip";
                contents[contents.Length - 1] = "SuccessMSG;";
                File.WriteAllLines(filepath, contents);
            }
        }
    
        public class ItemGrid
        {
            public string ItemName { set; get; }
            public bool ItemValue { set; get; }
        }
    }
    

    还有……

    // MainWindow.xaml.cs 
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.dataGridView.ItemsSource = HelperClass.ReadCsv(@"PathToRead\configuration.csv");
        }
    
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            var temp = new List<ItemGrid>();
            for (int i = 0; i < this.dataGridView.Items.Count; i++)
            {
                if (this.dataGridView.Items[i] is ItemGrid) // DataGrid pads it's item collection with elements we didn't add.
                    temp.Add((ItemGrid)this.dataGridView.Items[i]);
            }
            HelperClass.WriteCsv(temp, @"PathToSave\new_configuration.csv");
        }
    }
    

    【讨论】:

    • 嗨@WithMetta,非常感谢你!现在一切正常。两小时内拿到第一个Demo,申请就完成了!谢谢谢谢谢谢!!!
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多