Data Reader trimming the leading zeros
I have a string coming from a stored procedure looks like '001234567'.
sqlCommand = new SqlCommand("csp_Bbp_OBN_GetBasePageList", BBConnection);
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
sqlCommand.Connection.Open();
// Run the SQL statement, and then get the returned rows to the DataReader.
accReader = sqlCommand.ExecuteReader();
while (accReader.Read())
{
BasePage basePage = new BasePage();
basePage.GroupNum= accReader.GetValue(0).ToString().Trim();
basePageList.Add(basePage);
accReader.Close();
accReader.Dispose();
}
return basePageList;
In my case, from the stored procedure I am ret开发者_JAVA技巧urning the varchar, after executing and reading it I am getting the value to basePage.GrouNum which is a string. So, I don't see where it is trimming the leading zeros.
Example: GroupNumber in the table is : "001234567" BasePage.GroupNum after reading from DataReader : "1234567"
But, I do not want the leading zeros being trimmed. Can any one help me how to solve this problem?
You can convert it to an integer then format the string going out:
basePage.GroupNum = Convert.ToInt32(accReader.GetValue(0)).ToString("000000000")
Using the 0's as format specifiers should pad the result string appropriately.
If you have access to the stored procedure, make sure it returns a string. So:
select GroupNumber
instead of, for example:
select cast(GroupNumber as int) as GroupNumber
What happens if instead of
GetValue(0).ToString()
you use
GetString(0)
?
One other thing - get into the habit of wrapping things like commands and readers in using statements. You can avoid the close and dispose stuff and be assured even if your code throws you don't leave anything around.
精彩评论