Creating a custom format string in a dataGridView

余生长醉 提交于 2019-12-02 02:01:17

问题


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:


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;
            }
        }
    }



回答2:


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.



来源:https://stackoverflow.com/questions/2715710/creating-a-custom-format-string-in-a-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!