Click here to Skip to main content
15,307,395 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is the code where i can export data from datagridview to text files. BUT, the last row of the data was not there.

  Dim swWriter As New StreamWriter("D:\routes.txt") ' change path may be you haven't rights.
Dim LineToWrite As String = String.Empty

Try
    For _Row As Integer = 0 To DataGridView1.Rows.Count - 1
        LineToWrite = String.Empty
        For _Column As Integer = 0 To DataGridView1.Columns.Count - 1
            LineToWrite &= "," & DataGridView1.Rows(_Row).Cells(_Column).Value.ToString
        Next
        LineToWrite = LineToWrite.Remove(0, 1) 'remove the first comma
        swWriter.WriteLine(LineToWrite)
    Next
    swWriter.Flush()
    swWriter.Close()
    MessageBox.Show("Data Saved Successfully")
Catch ex As Exception
End Try



what should i do?
Posted
Updated 7-Sep-14 20:32pm
v4
Comments
MuhammadUSman1 8-Sep-14 1:10am
   
There is data available in datagridview or not?
NekoNao 8-Sep-14 1:13am
   
Yes there is data available. when i F10, I see data while debugging but still gets error of "Object reference not set to an instance of an object" in some part of the code where i cannot find.
MuhammadUSman1 8-Sep-14 1:18am
   
I think you haven't write to file in this path: C:\routes.txt
Please use desktop path or any other path. i.e : D:\routes.txt

if any issue then let me know.
NekoNao 8-Sep-14 1:21am
   
I can see a .txt file on C: but when I open it there is no data inside the text files. I change the path still got same error.
MuhammadUSman1 8-Sep-14 1:27am
   
Please Check Solution 2 i have pasted helping link also.
and simply use StreamWriter instead of FileStream may be it help you.
NekoNao 8-Sep-14 1:32am
   
Okay! It works well! Thank you! :)
NekoNao 8-Sep-14 2:25am
   
@MuhammadUSman1
I have problem. Although it was exported there are missing data. the last row is not in the .txt file, why is that?
MuhammadUSman1 8-Sep-14 5:50am
   
Dear please put breakpoint and debug code, it'll help you in learning and understanding what the exact issue is.
NekoNao 8-Sep-14 5:54am
   
I have put breakpoint. but still dont know exactly why it has error on it . check this . http://www.codeproject.com/Questions/816331/Connection-timeout-Object-reference-not-set-to-an?arn=0

Also check following link.

Reading from and Writing to Text Files
VB
' Dim fsStream As New FileStream("", FileMode.Create, FileAccess.Write) 
'also comment this may be fsStream not getting write properly, but according to me it should work.
        Dim swWriter As New StreamWriter("D:\routes.txt") ' change path may be you haven't rights.
        Dim LineToWrite As String = String.Empty
 
        Try
            For _Row As Integer = 0 To DataGridView1.Rows.Count - 1
                LineToWrite = String.Empty
                For _Column As Integer = 0 To DataGridView1.Columns.Count - 1
                    LineToWrite &= "," & DataGridView1.Rows(_Row).Cells(_Column).Value.ToString
                Next
                LineToWrite = LineToWrite.Remove(0, 1) 'remove the first comma
                swWriter.WriteLine(LineToWrite)
            Next
            swWriter.Flush()
            swWriter.Close()
            MessageBox.Show("Data Saved Successfully")
        Catch ex As Exception
        End Try


if any Issue then let me know.

-> M.U
   
v2
Comments
NekoNao 8-Sep-14 1:26am
   
Thanks! The values has been exported to the textfiles :)
MuhammadUSman1 8-Sep-14 1:28am
   
You Welcome
NekoNao 8-Sep-14 1:30am
   
Do you know how to export two datagridview (with FK) to an excel file?
MuhammadUSman1 8-Sep-14 1:32am
   
You are using single datagirdview or multiple gridview.
and you are using datatable or not? for databinding.
NekoNao 8-Sep-14 1:42am
   
CHECK THIS . this is my question . http://www.codeproject.com/Questions/814448/HOW-TO-EXPORT-A-PARENT-CHILD-DATAGRIDVIEW-TO-EXCEL
NekoNao 8-Sep-14 2:33am
   
Have problem in the last row is not exported
NekoNao 8-Sep-14 5:36am
   
It has error of NullReferenceException was unhandled.
An unhandled exception of type 'System.NullReferenceException' occurred in AllTrialApplication.exe
Addition information: object reference not set to an instance of an object
MuhammadUSman1 8-Sep-14 5:51am
   
On Which line you facing this issue. please put breakpoint and debug code...
NekoNao 8-Sep-14 5:55am
   
http://www.codeproject.com/Questions/816331/Connection-timeout-Object-reference-not-set-to-an?arn=0
To export data to Excel you have basically two options:

or
  • Export your data in the very simple CSV[^] file format (Google helps[^]). Since Excel is able to import data from a CSV file.
   
Use the Following C# code and make the appropriate changes:

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

   private void WriteDataFile()
   {
      string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
      string sql = @"select * from employee";
      SqlConnection conn = new SqlConnection(connString);
      string text="";
      try
      {
         conn.Open();
         SqlDataAdapter da = new SqlDataAdapter(sql, conn);
         DataSet ds = new DataSet();    
         da.Fill(ds, "employee");
         DataTable dt = ds.Tables["employee"];
         foreach (DataRow row in dt.Rows)
         {
	    text += "\r\n";
            foreach (DataColumn col in dt.Columns)
            {		
		text += row[col].ToString() + "  ";
            }
         }
         // Here Write the text in txt file

 	FileStream fs1 = new FileStream("D:\\Yourfile.txt", FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter writer = new StreamWriter(fs1);
        writer.WriteLine(text);
        writer.Close();

      }
      catch(Exception e)
      {
         Console.WriteLine("Error: " + e);
      }
      finally
      {
         conn.Close();
      }
   }  
   
Comments
NekoNao 8-Sep-14 3:14am
   
Whyd you think the last row is not exported?
NekoNao 8-Sep-14 5:36am
   
I cannot understand the code. Can you explain it?
Here is the Commented Code:

using System.IO;
 
   private void WriteDataFile()
   {
      // Initialize Connection string
      string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

      // Define Query to fetch Data From DatabaseTable
      string sql = @"select * from employee";

      // Initialize SQL Connection
      SqlConnection conn = new SqlConnection(connString);
      string text="";
      try
      {
	 // Initialize SQLDataAdapter to fetch data from tables
         SqlDataAdapter da = new SqlDataAdapter(sql, conn);

	 // Initialize DataSet
         DataSet ds = new DataSet();    

	 // Fill DataSet
         da.Fill(ds, "employee");

	 // Extract Data from DataSet in DataTable
         DataTable dt = ds.Tables["employee"];

	 // Loop to fetch Data From DataTable Row By Row
         foreach (DataRow row in dt.Rows)
         {
	    // Add New Line to Variable
	    text += "\r\n";

	    // Read a Row from DataTable & Add to text
            foreach (DataColumn col in dt.Columns)
            {		
		text += row[col].ToString() + "  ";
            }
         }
         // Here Write the text in txt file

	// Open File Stream in Which Data is to be Saved
 	FileStream fs1 = new FileStream("D:\\Yourfile.txt", FileMode.OpenOrCreate, FileAccess.Write);

	// Writing Data To Stream using StreamWriter
        StreamWriter writer = new StreamWriter(fs1);
	writer.WriteLine(text);

	//Close The Stram Writer 
        writer.Close();
        
	// Close File Stream
	fs1.Close();
      }
      catch(Exception e)
      {
         Response.Write("Error: " + e);
      }
      finally
      {
         conn.Close();
      }
   }  
   
Comments
CHill60 8-Sep-14 17:30pm
   
Please use the "Have a Question or Comment" links to make comments rather than posting more and more "solutions" ... also use the "Improve solution" link to update your answer. Posting multiple solutions is often viewed as "reputation point hunting" and will attract downvoters
Pl explain the exact requirement, whether you want to export the data from text file to database.

If this is so then define the delimiters in between the fields
   
Comments
NekoNao 8-Sep-14 1:05am
   
@MukeshSagar

I am just new in VB.Net ,..
I wanted to export data from datagridview to text files. so that i can use the text file to be exported as excel. because i am really having a hard time exporting from a parent/child datagridview to excel .

I have error encountered : "Object reference not set to an instance of an oject"
In that case use the DataSet which is used to fill the GridView.
Read row by row from DataSet and store in the StringBuilder variable.
After reading all rows save the file.
   
Comments
NekoNao 8-Sep-14 2:54am
   
Any example?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900