换行后删除最后一个字符

时间:2013-05-31 07:55:27

标签: vb.net

基本上我的功能是要清楚地分离数据集中的每个列数据

Public Shared Function mtdCDsToStr (ByVal pDs As DataSet) As String

Dim sResult As String = " "
Dim sb As New System.Text.StringBuilder
Dim dt As DataTable
Dim dc As DataColumn
Dim dr As DataRow
Dim i As Integer = 0

For Each dt In pDs.Tables
 For Each dr In dt.Rows
  For Each dc In dt.Columns
    sb.Append(dr(i).ToString + "|" + Environment.NewLine )

  Next

  sb.Remove(sb.Length -1, 1)
 Next
Next
sResult = sb.ToString
End Function

所以我的返回结果将类似于

结果 名1 | 名称2 | NAME3 | NAME4 |

|是我的数据分隔符,我试图删除|如果达到了最后的记录,但我没有成功

预期结果 名1 | 名称2 | NAME3 | NAME4

没有|在我的最后一条记录中

3 个答案:

答案 0 :(得分:0)

试试这个

For Each dt In pDs.Tables
 For Each dr In dt.Rows
  For Each dc In dt.Columns
    sb.Append(dc(i).ToString + iif(i=dt.Columns.Count-1,"","|") + Environment.NewLine )
    i += 1
  Next      
 Next
Next
sResult = sb.ToString

答案 1 :(得分:0)

试试这个:

删除|和新线。

sb.Remove(sb.Length -1 - Environment.NewLine.Length, Environment.NewLine.Length + 1)

只是删除|

    sb.Remove(sb.Length -1 - Environment.NewLine.Length, 1)

答案 2 :(得分:0)

你只需要替换

sb.Append(dr(i).ToString + "|" + Environment.NewLine )

 dim j as Integer = 0 // declare this above all the loops

 if j < dt.Columns.Count - 1 Then
     sb.Append(dr(i).ToString + "|" + Environment.NewLine )

我认为这会有所帮助,因为它会检查它是否不是最后一列,然后只会执行该语句,否则它将不会执行。

试试,我希望它会有所帮助.. :)