2015-10-20 62 views
0

我想從sql表中寫入數據到文本文件。如何將數據寫入文本文件無需排序

Dim Itemlist As New SortedList 

sql= select SONO,CustomerName,CustomerCode,ItemCode from tbl_SalesOrder where SONO =sonumber 

    commSQL = New SqlCommand(sql, cnnSQL) 
       drSQL = commSQL.ExecuteReader 
       While drSQL.Read 
         Dim values(drSQL.FieldCount - 1) As Object 
         Dim fieldCount As Integer = drSQL.GetValues(values) 
         Itemlist.Add(CStr(drSQL(0)) & "_" & CStr(drSQL(3)), values)  

       End While 

然後我寫這個數據到文本文件。

sr = New StreamWriter(AppPath & "\Import\SalesOrder.txt") 
       For j = 0 To Itemlist.Count - 1 

        Sono = CStr(DirectCast(Itemlist.GetByIndex(j), Object())(0)) 
        customername = CStr(DirectCast(Itemlist.GetByIndex(j), Object())(1)) 
        customercode = CStr(DirectCast(Itemlist.GetByIndex(j), Object())(2)) 
        Sitemcode = CStr(DirectCast(Itemlist.GetByIndex(j), Object())(3)) 
sql = Trim(Sono) & "|" & Trim(customername) & "|" & Trim(customercode) & "|" & Trim(Sitemcode) 
        sr.WriteLine(sql) 
    Next j 
       sr.Close() 
       Itemlist.Clear() 
       drSQL.Close() 

但這寫入sorting.my殼體drsql(3)之後的數據文本文件是該項目代碼,這個未來like.'12' , '25', '31', '45'。所以itemlist對這個值進行排序,並寫入這個文件。
我不想像這樣排序。我想寫入文本文件,如在表中的數據..如何我可以做到這一點。
任何幫助是非常可觀的。

+1

嗯,'ItemList'是'SortedList',爲什麼你會是驚訝於數據正在排序?如果你不希望數據被排序,那麼不要把它放到一個列表中排序。 – jmcilhinney

+0

先生我不想排序..所以我可以重新寫代碼? –

+0

我知道你不想排序。我讀過你的帖子,說你不想排序。這就是爲什麼我告訴你不要使用一個列表。如果你不想列表排序,爲什麼要使用'SortedList'?使用別的東西來存儲數據。 – jmcilhinney

回答

0

您使用的是SortedList,你可以使用ArrayList代替,或多個可重複使用,更漂亮,你可以使用這樣的代碼:

Dim connection = "your connection string" 
Dim command = "your command" 
Dim table As New System.Data.DataTable 
Dim adapter As New System.Data.SqlClient.SqlDataAdapter(command, connection) 
adapter.Fill(table) 

Dim builder As New System.Text.StringBuilder 
table.Rows.Cast(Of DataRow).ToList() _ 
    .ForEach(Sub(row) 
       builder.AppendLine(String.Join("|", _ 
       row.ItemArray.Select(Function(value) String.Format("{0}", value).Trim()))) 
      End Sub) 

System.IO.File.WriteAllText("your file path", builder.ToString()) 
+0

先生這將寫入所有數據到文本文件 –

+0

這是工作正常,謝謝,我可以問一個疑問 –

+0

歡迎您:)隨時問任何問題的答案:) –