Search code examples
c#wpfvalidationdatagrid

wpf datagrid : create a DatagridNumericColumn in wpf


I have a requirement that I want to make a datagridcolumn which only accepts numeric values(integer) ,when the user enter something other than numbers handle the textbox . I tried a lot of webpages ,Iam tired of these ,I greately appreciate anybody have the helping mind.


Solution

  • Based on @nit suggestion, you can create your own class derived from DataGridTextColumn like this:

    public class DataGridNumericColumn : DataGridTextColumn
    {
        protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
        {
            TextBox edit = editingElement as TextBox;
            edit.PreviewTextInput += OnPreviewTextInput;
    
            return base.PrepareCellForEdit(editingElement, editingEventArgs);
        }
    
        void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            try
            {
                Convert.ToInt32(e.Text);
            }
            catch
            {
                // Show some kind of error message if you want
    
                // Set handled to true
                e.Handled = true;
            }
        }
    }
    

    In the PrepareCellForEdit method you register the OnPreviewTextInput method to the editing TextBox PreviewTextInput event, where you validate for numeric values.

    In xaml, you simply use it:

        <DataGrid ItemsSource="{Binding SomeCollection}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding NonNumericProperty}"/>
                <local:DataGridNumericColumn Binding="{Binding NumericProperty}"/>
            </DataGrid.Columns>
        </DataGrid>
    

    Hope this helps