Search code examples
c#wpfwpf-controlswpfdatagrid

DataGrid cells - convert decimal and binary numbers to hexa


In my WPF application I have a DataTable populating a DataGrid, and there is the ability to edit cells in the DataGrid. I want, that in specific columns, if the user enters a decimal or binary number, it will change automatically to a hexadecimal number. Any ideas?


Solution

  • There are many ways to achieve your specified requirements. The method described in the comments was to handle the DataGrid.CellEditEnding event.

    <DataGrid ItemsSource="{Binding Items}" CellEditEnding="DataGrid_CellEditEnding" />
    

    From the linked page, this event:

    Occurs before a cell edit is committed or canceled.

    So, after a user has finished typing a value in any cell, this event will be raised. Therefore, all you need to do now is to call a conversion method from this event handler:

    private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        ((TextBox)e.EditingElement).Text = 
            ConvertToHexadecimal(((TextBox)e.EditingElement).Text);
    }
    
    private string ConvertToHexadecimal(string input)
    {
        int number = 0;
        bool isInputInteger = int.TryParse(input, out number); 
        return isInputInteger ? number.ToString("X") : input; 
    }