Is it possible to add a row in the middle of a datagrid table

vitaminchik 426 Reputation points
2023-11-07T22:14:58.1666667+00:00

Hi all. Does datagrid support adding rows beyond the bottom of the table? For example, if there is a table of 5 rows and I would like to add a row on the 2nd row.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,558 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,480 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 23,216 Reputation points Microsoft Vendor
    2023-11-08T02:18:00.21+00:00

    Hi,@vitaminchik. Welcome to Microsoft Q&A Forum.

    For the problem of adding a row in the middle of the datagrid table, you could do this by adding the item to the datagrid's ItemsSource. Here is a complete code example that demonstrates how to add rows to a DataGrid based on a specific index provided in a TextBox:

     <StackPanel>
                <DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="True" Grid.Row="0" />
                <TextBox Text="{Binding NewRowIndex}" Grid.Row="1" />
                <Button Content="Add Row" Command="{Binding AddRowCommand}" Grid.Row="1" HorizontalAlignment="Right" />
            </StackPanel>
    

    Codebedhind:

    
     public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                DataContext = new MainViewModel();
       }
    }
    
    
     public class MainViewModel : ViewModelBase
        {
            private int _newRowIndex;
            public int NewRowIndex
            {
                get { return _newRowIndex; }
                set { SetValue(ref _newRowIndex, value); }
            }
    
            private ObservableCollection<CustomData> _rows;
            public ObservableCollection<CustomData> Rows
            {
                get { return _rows; }
                set { SetValue(ref _rows, value); }
            }
    
            public RelayCommand AddRowCommand { get; private set; }
    
            public MainViewModel()
            {
                Rows = new ObservableCollection<CustomData>   
                {
                    new CustomData { Name = "John", Age = 30 },
                    new CustomData { Name = "Jane", Age = 25 },
                    new CustomData { Name = "Doe", Age = 40 },
                    new CustomData { Name = "Smith", Age = 35 },
                    new CustomData { Name = "Alex", Age = 28 }
                };
    
                AddRowCommand = new RelayCommand(AddRow);
            }
    
           
            private void AddRow(object param)
            {
            
                    if (NewRowIndex >= 1 && NewRowIndex <= Rows.Count)
                    {
                        Rows.Insert(NewRowIndex, new CustomData { Name = " ", Age = 0 });
                    }
                    else
                    {
                        MessageBox.Show("Invalid index. Please provide a valid index within the range.");
                    }
              
              
            }
        }
        public class RelayCommand : ICommand
        {
            private readonly Action<object> _execute;
            private readonly Predicate<object> _canExecute;
    
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute(parameter);
            }
    
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            public void Execute(object parameter)
            {
                _execute(parameter);
            }
        }
    
    
        public class ViewModelBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                var handler = PropertyChanged;
                if (handler != null)
                    handler(this, new PropertyChangedEventArgs(propertyName));
            }
            protected virtual void SetValue<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
            {
                field = value;
                OnPropertyChanged(propertyName);
            }
        }
        public class CustomData
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
    
    

    The result:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.