hello !
this is my code , i am writing a text file form the datagrid, but this code is very slow , please check it out and give me some advice how i can make my code fast ,

 If IO.File.Exists("C:\Customers.txt") = False Then
            IO.File.Create("C:\Customers.txt")
        End If

        Dim FILE_NAME As String = "C:\Customers.txt"

        If System.IO.File.Exists(FILE_NAME) = True Then
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
            Dim i As Integer
            Dim strheading As String
            strheading = "CustomerID           CustomerName"
            objWriter.WriteLine(strheading)
            For i = 0 To dgvMain.Rows.Count - 1
                Dim str As String
                str = dgvMain.Item(0, i).Value.ToString() & "                " & dgvMain.Item(1, i).Value.ToString()
                objWriter.WriteLine(str)
            Next
            objWriter.Close()

if you have better code then this please show me so that i can complete my current task.

Best Regards

Muhammad Waqas Aslam

How bout you give the StringBuilder a go?
Import SYSTEM.TEXT

    If IO.File.Exists("C:\Customers.txt") = False Then
      IO.File.Create("C:\Customers.txt")
    End If
    Dim FILE_NAME As String = "C:\Customers.txt"

    If System.IO.File.Exists(FILE_NAME) = True Then
      Dim sb As New StringBuilder

      sb.AppendLine("CustomerID           CustomerName")
      For i As Integer = 0 To dgvMain.Rows.Count - 1
        sb.AppendLine(dgvMain.Item(0, i).Value.ToString() & "                " & dgvMain.Item(1, i).Value.ToString())
      Next
      Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
      objWriter.WriteLine(sb.ToString)

      objWriter.Close()
    End If

How many items do you have in your datagrid and what do you define as "slow"? How long is it taking to complete the loop? Do you get consistent times on successive runs? Do you have anything else running that could be sucking back CPU cycles?

thanks kRod and jim for your time , well i have 25000+ records in my grid , it takes very long to complete .and there is nothing runing with it.

Regards

well i got solution of my prob , now i am directly writing all the records from the datatable, like this

dim con as new sqlconnection ("connectionstring")
con.open()
dim da as new sqldataadapter("query",con)
dim dt as new datatable 
da.fill(dt)
 For Each dtr As DataRow In dt.Rows
                    Dim str As String
                    str = dtr.Item(0).ToString & " " &  dtr.Item(1).ToString 
                    objWriter.WriteLine(str)
 Next

this is very fast and simply the best so far :P ,
but thank you both of you , :)

Regards

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.