Creating a custom format string in dataGridView

I have a dataGridView whose dataSource is dataTable.

My problem is that I want certain columns to appear in the Hex column. I can go this far using something like this:

foreach (DataGridViewColumn c in grid.Columns) { if (DISPLAYED_IN_HEX.Contains(c.Name)) { c.DefaultCellStyle.Format = "X"; } } 

My problem is that I want this hexadecimal value to be added with 0x so as not to confuse anyone with the fact that they are in hexadecimal form. The values ​​in the data table are various integer types. I thought about creating a custom IFormatProvider, but I don’t think my coding skills are still there. Any other possible solutions?

+2
tostring c # formatting
source share
2 answers

Yes, the CellFormatting event will be great. Here's an example one, it tries to convert the decimal number in the first column to hex:

  private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 0 && e.Value != null) { long value = 0; if (long.TryParse(e.Value.ToString(), out value)) { e.Value = "0x" + value.ToString("X"); e.FormattingApplied = true; } } } 
+3
source share

Not the most efficient way, maybe, but maybe you could handle the CellFormatting event, and then change the formatting based on cell by cell.

+1
source share

All Articles