简体   繁体   中英

How to save content of DataTable to a text file in C#

I have a Windows Forms application, where I have created 2 different buttons.

The first button inserts data to the DataTable, here:

        public void button1_Click(object sender, EventArgs e)
        {
           
            var salesman = new Salesman();

           
            salesman.Name = txtName.Text;
            salesman.SecurityNumber = txtSecurity.Text;
            salesman.District = txtDistrict.Text;
            salesman.AmountSold = int.Parse(txtAmount.Text);
            
           
            
            DataTable information = new DataTable();
            information.Columns.Add("Namn");
            information.Columns.Add("Personnummer");
            information.Columns.Add("Distrikt");
            information.Columns.Add("Antal artiklar", typeof(int));

            
            DataRow row = information.NewRow();
            row["Namn"] = salesman.Name;
            row["Personnummer"] = salesman.SecurityNumber;
            row["Distrikt"] = salesman.District;
            row["Antal artiklar"] = salesman.AmountSold;
            information.Rows.Add(row);

        
            foreach (DataRow Drow in information.Rows)
            {

                int num = dataGridView1.Rows.Add();
                dataGridView1.Rows[num].Cells[0].Value = Drow["Namn"].ToString();
                dataGridView1.Rows[num].Cells[1].Value = Drow["Personnummer"].ToString();
                dataGridView1.Rows[num].Cells[2].Value = Drow["Distrikt"].ToString();
                dataGridView1.Rows[num].Cells[3].Value = Drow["Antal artiklar"];

            }

            if (salesman.AmountSold < 50)
            {
                levelOne++;
                label8.Text = Convert.ToString(levelOne);

            }

            if (salesman.AmountSold >= 50 && salesman.AmountSold < 99)
            {
                levelTwo++;
                label12.Text = Convert.ToString(levelTwo);
            }

            if (salesman.AmountSold >= 100 && salesman.AmountSold < 199)
            {
                levelThree++;
                label13.Text = Convert.ToString(levelThree);
            }

            if (salesman.AmountSold >= 199)
            {
                levelFour++;
                label14.Text = Convert.ToString(levelFour);
            }

           
            txtName.Text = "";
            txtSecurity.Text = "";
            txtDistrict.Text = "";
            txtAmount.Text = "";

        }

My second button needs to take all this stored data (from Salesman class and labels etc...) to a textfile. The validation does not matter or format, I just want plain simple text. Here is my code for that button:

        private void button3_Click(object sender, EventArgs e)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\skrivbord\\Borna.txt");

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for(int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    file.Write("" + dataGridView1.Rows[i].Cells[j].Value.ToString()+"\t"+"|");
                }
                file.WriteLine("");
                file.WriteLine("");
            }
            file.Close();
            MessageBox.Show("Din fil är hämtad");
        }

Right now, the program only shows the MessageBox when trying to save a file. Nothing else. What am I doing wrong here, and can I get some guidance since I am new to C# and .NET please.

Kind regards

To write to a file, you can use the File class and the WriteAllText method.

private void button3_Click(object sender, EventArgs e)
{
  var txtFile = new StringBuilder();
  for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
  {
      string line = "";
      for (int j = 0; j < dataGridView1.Columns.Count; j++)
      {
          line += dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|";
      }
      txtFile.AppendLine(line);
  }

  string fileName = @"C:\\skrivbord\\Borna.txt";
  System.IO.File.WriteAllText(fileName, txtFile.ToString());
}

Or you can use the following code

private void button3_Click(object sender, EventArgs e)
{
    using (StreamWriter file = new StreamWriter((@"C:\\skrivbord\\Borna.txt"))
    {
       for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
       {
           string line = "";
           for(int j = 0; j < dataGridView1.Columns.Count; j++)
           {
              line = dataGridView1.Rows[i].Cells[j].Value.ToString()+"\t"+"|";
           }
           file.WriteLine(line);
           file.WriteLine("");
       }
    }
    MessageBox.Show("Din fil är hämtad");
}

try this

    StreamWriter file = new StreamWriter("C:\\skrivbord\\Borna.txt")

or

    StreamWriter file = new StreamWriter(@"C:\skrivbord\Borna.txt")        

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