Leading zeros are not adding to DataTable columns with PadLeft or String.Format.
Initially I copied user uploaded excel data to Datatable. I'm trying to add zeros in front of datatable column values if the length is less than 8 digits and after that I have to compare with another table for matching records. If I don't have leading zeros I'm missing those records while matching with other datatable columns. But I want them to be with leading zeros so they can be matched to get correct results.
Ex: I have a column "CODE" in datatable with values 30500, 501080, 5020900, 19010300 etc and Would like to have my results like 00030500, 00501080, 05020900, 19010300
Note: I would like the change the data in the Datatable not in the sql query which retrieves the data. I don't want code for converting int to string leading zeros. Even I tried in that way didn't fix my issue.
I tried couple of ways but it didn't solve. What's wrong with my code. It's not working. I used below from How to add leading zeros in DataTable columns but still not changed anything. Don't consider this post as duplicate, As I tried all ways but still the problem exist, Hence posting here.
Approach 1:
foreach (DataRow row in dataExcelInputTable.Rows)
{
row["CODE"] = row["CODE"].ToString().PadLeft(8, '0');
}
dataExcelInputTable.AcceptChanges();
Approach 2:
foreach (DataRow drin dataExcelInputTable.Rows)
{
dr["CODE"] = String.Format("{0:00000000}", int.Parse(dr["CODE"].ToString()));
}
dataExcelInputTable.AcceptChanges();
Approach 3:
int countSize = 0;
int val = 0;
foreach (DataRow row in dataExcelInputTable.Rows)
{
countSize = row["CODE"].ToString().Length;
val = int.Parse(row["CODE"].ToString());
if (countSize < 8)
{
row["CODE"] = val.ToString("D8");
//Response.Write("<br/>" + val.ToString("D8"));
}
}
dataExcelInputTable.AcceptChanges();
Update:
foreach (DataRow row in dataExcelInputTable.Rows)
{
if (row["CODE"].ToString().Length < 8)
{
row["CODE"] = row["CODE"].ToString().PadLeft(8, '0');
}
Response.Write("<br/>" + row["CODE"]);
}
dataExcelInputTable.AcceptChanges();
Right now its printing below, its not padding zero front.
9040100 (<8) , 9070100 (<8) , 9090200 (<8) , 9090300 (<8)
10020300 (=8) , 10030300 (=8) , 11010100 (=8)