Kevin
Kevin

Reputation: 4848

How can I format the value when adding it to a DataGridView column?

I have a line of code that puts a value into a DataGridView column:

dataGridView1.Rows[r].Cells[2].Value = MBRHISTDETLDt.Rows[r].ItemArray[0];

The value going in is a text field that looks like this:

"00001100914401"

I'd like to format it so that it looks like the following when adding it to the column:

"110-09-144.01"

Basically, I'd like to trim all leading zeros and have the remaining number in the format ###-##-##.##.

I think I can use the TrimStart() method of the String class to remove the leading zeros, but I'm not sure about an easy way to format the rest of the string without substringing it and inserting the dashes and period. I'm hoping there's an easier way. Any advice would be greatly appreciated!

Thanks!

Upvotes: 0

Views: 408

Answers (1)

Chandu
Chandu

Reputation: 82893

Try this:

String value = MBRHISTDETLDt.Rows[r].ItemArray[0].ToString(); 
value  = Regex.Replace(value.TrimStart('0'), @"^(\d{3})(\d{2})(\d{3})(\d*)$", "$1-$2-$3.$4");
dataGridView1.Rows[r].Cells[2].Value = value;

Upvotes: 3

Related Questions