我正在尝试从数据库Microsoft SQL中检索我的记录并将其写入.txt文件。我的代码工作正常,但PadRight()不是。
我的问题是:为什么我的PadRight()不起作用? *即使我将PadRight()放在其他列名中,它仍然无效。
输出:如果我放行(“ProcessDate”.PadRight(9)),它应该只显示6字符值而不是整个值。
例如:如果来自数据库Microsoft SQL的ProcessDate的值是 11/8/2016 31342 输出应该是:2016年11月8日
我的代码:
For Each row As DataRow In table.Rows
swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
row("ProcessDate".PadRight(6)),
row("SubscriberAccountNumber"),
row("PayorName"),
row("ParNumber"),
row("MemberType"),
row("ApplicablePeriodStart"),
row("ApplicablePeriodEnd"),
row("TransactionAmount"),
row("PaymentType"),
row("CheckNo")))
count += 1
Next
答案 0 :(得分:1)
PadRight
方法在字符串中对齐并添加空格(默认情况下)。
如果总宽度小于字符串长度,则它将返回对原始字符串的引用。
所以,它不会缩短你的字符串。
我很高兴你看看Substring方法。
正如ChrisF在评论中所提到的,Substring解决方案将仅部分地解决问题。
如果row("ProcessDate")
肯定会给您一个有效的日期,那么您只需更改"{0:dd/MM/yyyy}{1}{2}{3}{4}{5}{6}{7}{8}{9}"
的格式字符串。
如果它可以是Nothing
,您可以使用许多解决方案解决此问题,我将发布一个。
For Each row As DataRow In table.Rows
Dim dt As DateTime
Dim finalValue As String = If(DateTime.TryParse(row("ProcessDate"), dt), dt.ToString("dd/MM/yyyy"), "Default value")
swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
finalValue,
row("SubscriberAccountNumber"),
row("PayorName"),
row("ParNumber"),
row("MemberType"),
row("ApplicablePeriodStart"),
row("ApplicablePeriodEnd"),
row("TransactionAmount"),
row("PaymentType"),
row("CheckNo")))
count += 1
Next
答案 1 :(得分:0)
For Each row As DataRow In table.Rows
Dim dt As DateTime
Dim finalValue As String = If(DateTime.TryParse(row("ProcessDate"), dt), dt.ToString("dd/MM/yyyy"), "Default value")
Dim SubscriberNumber As String = row("SubscriberAccountNumber")
Dim PayorName As String = row("PayorName")
Dim ParNumber As String = row("ParNumber")
Dim MemberType As String = row("MemberType")
Dim Start As String = row("ApplicablePeriodStart")
Dim Ends As String = row("ApplicablePeriodEnd")
Dim Amount As String = Convert.ToDouble(row("TransactionAmount"))
Dim PaymentType As String = row("PaymentType")
Dim CheckNo As String = row("CheckNo")
swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", finalValue.PadRight(15), SubscriberNumber.PadRight(20), PayorName.PadRight(30), ParNumber.PadRight(20), MemberType.PadRight(20), Start.PadRight(6), Ends.PadRight(6), Amount.PadRight(15), PaymentType.PadRight(10), CheckNo.PadRight(25)))
count += 1
Next
我找到了另一个解决方案。 =)