views:

204

answers:

2

I have a dataGridView whose dataSource is a dataTable.

My problem is that I want certain columns to be displayed in Hex. I can get that far with using something like this:

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

            }
        }

My issue though is that I want this hex value prepended with 0x so as not to confuse anyone that they are in hexidecimal form. The values in the dataTable are various integral types. I looked into creating a custom IFormatProvider, but I don't think my coding skills are up to that par yet. Any other possible solutions?

+1  A: 

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

ho1
Inside the CellFormatting event, you can capture the column you want to format with the EventArgs. By modifying the e.Value property with whatever string you'd like, you'll be able to reformat the string as needed. If you do make any modifications, make sure you check e.FormatApplied to true.
greggorob64
the problem is the data type is not a string, so I can't just change the value of it to have the 0x in front of it.
Andy
You could change it to be a string and then add 0x in frontand you could store the original value in the cells Tag property. Atleast if it's just to present information, if you need to write it back to the DataTable I'm not sure.
ho1
I don't have access to anything about a dataType with the DataGridViewCellFormattingEventArgs. I can set e.value to the string I want, but it seems to update the dataTable automatically, and that's where the exception gets thrown about string->int.
Andy
Strange, I just checked, and I've got a datagrid that gets populated from a DataTable and I format both `double` and `DateTime` fields to strings without any problems (unless it quietly converts them back, but I add a currency sign to the double). All I do is something similar to `e.Value = FormatAsMyString(e.Value`);.
ho1
+1  A: 

Yes, the CellFormatting event will do just fine. Here's an example one, it tries to convert a 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;
            }
        }
    }
Hans Passant
Thanks, even though greggorob64 explicitly said to, I forgot the linee.FormattingApplied = true;
Andy