I have strings that are being converted that need to be four characters long. The values are coming in as anywhere between 0 and 4 characters long. I need to pad the strings with zeros to make all IDs 4 characters long:
Example
Input number Need
1 => 0001
121 => 0121
0567 => 0567
So far I have tried:
int temCode = 0;
DataTable dt = objSites.Get_Max_SiteCode();
if (dt.Rows.Count > 0)
{
string siteCode = dt.Rows[0]["SiteCode"].ToString();
string code = siteCode.Substring(siteCode.Length - 4);
temCode = Convert.ToInt32(code) + 1;
temCode.ToString().PadLeft(4, '0'); // same number is coming here without any pad left.
}
You're not doing anything with the result of PadLeft
- but you don't need to do that anyway. You can just specify the number of digits (and format) in the ToString
call:
string result = temCode.ToString("d4");
See more on this question at Stackoverflow