Padleft没有添加前导零

时间:2014-02-19 17:36:14

标签: c# formatting string-formatting

我在代码中添加了PadLeft(8,'0'),以确保插入到数据库表中的所有帐户的长度至少为8个字符。这是代码:

public static string CleanAccount(String strVal)
{
    string cleanValue;
    string paddedAccount = strVal.PadLeft(8,'0');
    //MessageBox.Show("account: " + paddedAccount);

    if (paddedAccount == null)
    {
        throw new System.ArgumentException("Value cannot be null", "original");
    }
    else
    {
        cleanValue = paddedAccount.Replace(" ", "").Replace("$", "").Replace("-", "");
    }

    return cleanValue;
}

Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = worksheet.UsedRange;

long fullRow = worksheet.Rows.Count;
long lastRow = worksheet.Cells[fullRow, 1].End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
int colCount = xlRange.Columns.Count;

for (int i = 2; i <= lastRow; i++)
{
    lstTran.Add(new LegalTransactionRec()
                    {
                        AccountNumber = Form1.CleanAccount(xlRange.Cells[i, 1].Value2.ToString()),
                        CostAmount = Form1.CleanAmount(Form1.TryToParse(xlRange.Cells[i, 3].Value2.ToString())),
                        SSN = Form1.CleanString(xlRange.Cells[i, 6].Value2.ToString()),
                        TransactionDate = Form1.ConvertToDateTime(xlRange.Cells[i, 2].Value),
                        Description = Form1.CleanDescription(xlRange.Cells[i, 8].Value2.ToString()),
                        TransactionCode = Form1.CleanTranCode(Form1.CleanExtra(xlRange.Cells[i, 4].Value2.ToString()))
                    }
               );
}

MessageBox没有被注释掉时,我看到该帐户确实被填充,但在它被添加到数据库表后,它显示没有前导零。这会发生什么原因?

1 个答案:

答案 0 :(得分:1)

错误是一个用户,我在发布的帖子的评论中发现了Hans Passant同时提到的错误。

以下是我的代码中的更改:

sql.AppendLine(trans.AccountNumber + ",");

sql.AppendLine("'" + trans.AccountNumber + "',");