简体   繁体   中英

How to export data from database to a textfile using linq

I wonder how to export data from a DataBase table to a text file using Linq.

The database table name is Customer and columns are CustomerID and Customername .

I use StreamWriter and I want to fill the text file with the data that's in the database table Customer .

This works - but this exporting from DataGridView

 private void bExportEKsystem_Click(object sender, EventArgs e)
 {
     TextWriter sw = new StreamWriter("Test.txt", true);

     int rowcount = DataGridview1.Rows.Count;
     for (int i = 0; i < rowcount - 1; i++)
     {
         sw.WriteLine();
     }

    sw.Close();    
 }

You can do something like this:

IEnumerable<Customer> customers = from customer in db.Customer 
    select CustomerID,   Customername;

using(TextWriter sw = new StreamWriter("test.txt", true))
{
    foreach (var c in customers)
    {
        sw.WriteLine(c.ToString());
    }
}

Where you define your Customer.ToString to print out customer info in your preferred format...

Try This:

        int rowcount = datagridview1.Rows.Count;
        IEnumerable<string> output = datagridview1.Rows.Cast<DataGridViewRow>().Select( row => (string) row.Cells[0].Value + row.Cells[1].Value);
        using(TextWriter sw = new StreamWriter("test.txt", true))
        {
            foreach (string s in output)
            {
                   sw.WriteLine(s);
            }            
        }

*edit: it's better to use the using statement for the Stream

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