c#在txt文件中写入DataTable行

时间:2016-10-07 13:37:05

标签: c# datatable

我在DataTable显示的DataGridView上有40行 我很困惑为什么我的方法只保存One Row中的TextFile

    private void SaveBtn_Click(object sender, EventArgs e)
    {
        String outputFile;
        List<String> ListData = new List<String>();
        using (SaveFileDialog sfd = new SaveFileDialog())
        {
            sfd.Filter = "Txt File|*.Txt";
            if (sfd.ShowDialog() != DialogResult.OK)
                return;
            outputFile = sfd.FileName;
        }

        DataTable tb = pw.SavedInfo(User_info.UserID);

        for (int i = 0; i < tb.Rows.Count; i++)
        {
           ListData.Add("Name==> " + tb.Rows[i][1].ToString() + "  LastName ==> " + tb.Rows[i][2].ToString() + "  Email ==> " + tb.Rows[i][3].ToString() );

        }

        foreach (String s in ListData)
        {
            using (TextWriter Tw = new StreamWriter(outputFile))
            {
                Tw.WriteLine(s);
            }               
        }
    }

我错过了什么吗?因为这是一个非常漫长的一天,以保持专注

2 个答案:

答案 0 :(得分:2)

使用相同的StreamWriter

using (TextWriter Tw = new StreamWriter(outputFile))
{
    foreach (String s in ListData)
    {
        Tw.WriteLine(s);             
    }
}

或使用constructor that takes a boo l代表“追加”:

foreach (String s in ListData)
{
    using (TextWriter Tw = new StreamWriter(outputFile, true))
    {
        Tw.WriteLine(s);
    }               
}

答案 1 :(得分:2)

File.WriteAllLines(outputFile, lisData);

使用它来写入文件。 File.WriteAllLines Documentation