C#csv帮助保存信息 [英] C# csv helper save infomation

查看:71
本文介绍了C#csv帮助保存信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在应用程序打开时编写一个新的.csv文件,但是如果我想编辑现有的.csv文件并重写它,我会得到一个空白的datagride。我怎么绕过那个?



我尝试过:



I can write a new .csv file when the app opens but if I want to edit a existing .csv file and rewrite it I get a blank datagride. how do I get around that?

What I have tried:

       private void btnWrite_Click(object sender, EventArgs e)
        {
           

                using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "csv|*.csv", ValidateNames = true })
                {
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        using (var sw = new StreamWriter(sfd.FileName))
                        {
                            var writer = new CsvWriter(sw);
                            writer.WriteHeader(typeof(Lunch));

                            if (lunchBindingSource == null || lunchBindingSource.DataSource == null)
                            {
                                MessageBox.Show("Error in Saving.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }


                            foreach (Lunch s in lunchBindingSource.DataSource as List<Lunch>)
                            {
                                writer.WriteRecord(s);
                            }
                        }
                        MessageBox.Show("Your Data has been Successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
        }
         

private void btnRead_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    
                        var sr = new StreamReader(new FileStream(ofd.FileName, FileMode.Open));
                        var csv = new CsvReader(sr);
                          lunchBindingSource.DataSource = csv.GetRecords<Lunch>().ToString();
                        lunchBindingSource.DataSource = csv.GetRecords<Lunch>(); /// use to create file
                    }
               }
            }

推荐答案

开始(如NotPoliticallyCorrect所说)不忽略异常。

当您编写如下代码时:

Start by (as NotPoliticallyCorrect says) not ignoring exceptions.
When you write code like this:
try
{
	... code ...
}
catch (Exception ex)
{
}

你故意丢弃任何信息可能会出现导致问题的原因。这有点像在汽车上穿刺而只是把音乐转向淹没噪音 - 它会在以后回来咬你,比你停下来看看问题要困难得多!

因此,将代码添加到 catch 块以报告问题 - 例如MessageBox(如果这是WinForms或WPF应用程序)。

然后在Read按钮单击处理程序中使用行在上放置一个断点,并逐步调试调试器中的代码,以确切了解发生了什么以及何时发生。



您需要信息 - 我们无法为您提供信息,因为我们无法访问您的数据!

You are deliberately throwing away any information that might be available on what is causing a problem. It's a bit like getting a puncture in the car and just turning the music up to drown out the noise - it will come back to bite you later, and a lot harder than if you had stopped and looked at the problem!
So add code to your catch block to report the problem - a MessageBox for example (if this is a WinForms or WPF app).
And then put a breakpoint on the using line in your Read button click handler and step through the code in the debugger to see exactly what is happening and when.

You need information - and we can't get it for you, as we don't have access to your data!


As你被告知,从你的代码中删除 try / catch

try / catch 在这里隐藏代码中的失败,以及失败的原因和位置。

建议:在你确切知道为什么这样做之前,永远不要使用try / catch。并且在你完成代码调试之前一直使用它。



当你不理解你的代码在做什么或为什么它做它做的时候,答案是 debugger

使用调试器查看代码正在执行的操作。它允许你逐行执行第1行并在执行时检查变量,它是一个令人难以置信的学习工具。



调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做的比较。

调试器中没有魔法,它没有找到错误,它只是帮助你。
As you have been told, remove the try/catch from your code.
The try/catch is here to hide failures in your code, and the reason and the position of failure.
Advice: never use try/catch until you know exactly why you do it. And use it until you finished debugging your code.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. It allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to.


我添加了这个一段代码并解决了问题。



I added this piece of code and fixed the issue.

lunchBindingSource.ResetBindings(false);
                 
                        var lunchList = lunchBindingSource.List as IList<Lunch>;
                        foreach (Lunch s in lunchList)
                        {
                            writer.WriteRecord(s);
                        }


这篇关于C#csv帮助保存信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆