Aktualizacja dataGridView po odebraniu danych działa tylko za pierwszym razem

0

Po odebraniu danych robię aktualizacje dataGridView.

 foreach (var zdarzenia in awarie_gotowe)
                {
                    dataGridView1.Rows.Add(zdarzenia.data_awari, zdarzenia.awaria);
                }
 

Wszystko ładnie pięknie ale tylko za 1 razem. Potem dataGrid się nie odświeża.
Próbowałem dodać przed forech

 
dataGridView1.Rows.Clear();

ale efekt jest tylko taki, że grid zostaje pusty...

Proszę o porady

2

Witaj,

Zainteresuj się czym jest ObservableCollection. Są to specjalizowane rodzaje kolekcji, które posiadają automatyczny mechanizm rozgłaszania zmian w nich dokonanych. Przykładowo:

using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Accidens.App.Common;
using Accidens.App.Data.Model;
using Accidens.App.ViewModels;

namespace Accidens.App
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new AccidentsViewModel();
        }
    }

    namespace Data.Model
    {
        // Awaria
        public class Accident
        {
            public DateTime Created { get; set; } //Utworzono
            public Guid AccidentKindId { get; set; } //Identyfikator rodzaju awarii
        }
    }

    namespace ViewModels
    {
        public class AccidentsViewModel
        {
            public ObservableCollection<Accident> DoneAccidents { get; set; }
            public ICommand AddAccidentCommand { get; set; }

            public AccidentsViewModel()
            {
                DoneAccidents = new ObservableCollection<Accident>
                {
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 15, 0),
                        AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                    },
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 18, 0),
                        AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                    },
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 22, 0),
                        AccidentKindId = new Guid("bdac1b08-716e-47ee-9eae-91b114235103")
                    }
                };

                AddAccidentCommand = new RelayCommand(AddAccident);
            }

            public void AddAccident()
            {
                DoneAccidents.Add(new Accident()
                {
                    Created = new DateTime(2015, 8, 11, 22, 15, 0),
                    AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                });
            }
        }
    }

    namespace Common
    {
        public class RelayCommand : ICommand
        {
            private readonly Action _execute;
            private readonly Func<bool> _canExecute;

            /// <summary>
            /// Raised when RaiseCanExecuteChanged is called.
            /// </summary>
            public event EventHandler CanExecuteChanged;

            /// <summary>
            /// Creates a new command that can always execute.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            public RelayCommand(Action execute)
                : this(execute, null)
            {
            }

            /// <summary>
            /// Creates a new command.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            /// <param name="canExecute">The execution status logic.</param>
            public RelayCommand(Action execute, Func<bool> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
                _execute = execute;
                _canExecute = canExecute;
            }

            /// <summary>
            /// Determines whether this <see cref="RelayCommand"/> can execute in its current state.
            /// </summary>
            /// <param name="parameter">
            /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
            /// </param>
            /// <returns>true if this command can be executed; otherwise, false.</returns>
            public bool CanExecute(object parameter)
            {
                return _canExecute == null || _canExecute();
            }

            /// <summary>
            /// Executes the <see cref="RelayCommand"/> on the current command target.
            /// </summary>
            /// <param name="parameter">
            /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
            /// </param>
            public void Execute(object parameter)
            {
                _execute();
            }

            /// <summary>
            /// Method used to raise the <see cref="CanExecuteChanged"/> event
            /// to indicate that the return value of the <see cref="CanExecute"/>
            /// method has changed.
            /// </summary>
            public void RaiseCanExecuteChanged()
            {
                var handler = CanExecuteChanged;
                if (handler != null)
                {
                    handler(this, EventArgs.Empty);
                }
            }
        }
    }
}
 

i xaml:

<Window x:Class="Accidens.App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:viewModels="clr-namespace:Accidens.App.ViewModels"
        d:DataContext="{d:DesignInstance viewModels:AccidentsViewModel, d:IsDesignTimeCreatable=True}"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" >
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>
        <DataGrid
            Grid.Row="0"
            ItemsSource="{Binding DoneAccidents}"
            AutoGenerateColumns="True" />
        <Button Grid.Row="1" Command="{Binding AddAccidentCommand}" Content="Dodaj" Width="100" HorizontalAlignment="Right" />
    </Grid>
</Window>

Warto zapoznać się z np. wzorcem MVVM i zacząć wykorzystywać dedykowane sposoby wiązania danych.

Pozdrawiam,
Maciej

2

Qrcze! Jakoś się zasugerowałem, że piszesz w WPF :)
Nie dużo pamiętam z WinFormsów, ale zamiast ObservableCollecton trzeba zastosować BindingList, a kod pozostanie podobny:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using WindowsFormsApplication1.Data.Model;
using WindowsFormsApplication1.ViewModels;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private readonly AccidentsViewModel _viewModel;

        public Form1()
        {
            InitializeComponent();
            _viewModel = new AccidentsViewModel();
            dataGridView2.DataSource = _viewModel.DoneAccidents;
            
        }

        private void AddAccident_Click(object sender, EventArgs e)
        {
            _viewModel.AddAccident();
        }
    }

    namespace Data.Model
    {
        // Awaria
        public class Accident
        {
            public DateTime Created { get; set; } //Utworzono
            public Guid AccidentKindId { get; set; } //Identyfikator rodzaju awarii
        }
    }

    namespace ViewModels
    {
        public class AccidentsViewModel
        {
            public BindingList<Accident> DoneAccidents { get; set; }

            public AccidentsViewModel()
            {
                DoneAccidents = new BindingList<Accident>
                {
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 15, 0),
                        AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                    },
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 18, 0),
                        AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                    },
                    new Accident()
                    {
                        Created = new DateTime(2015, 8, 11, 22, 22, 0),
                        AccidentKindId = new Guid("bdac1b08-716e-47ee-9eae-91b114235103")
                    }
                };
            }

            public void AddAccident()
            {
                DoneAccidents.Add(new Accident()
                {
                    Created = new DateTime(2015, 8, 11, 22, 15, 0),
                    AccidentKindId = new Guid("7e4f364f-c3ae-40a7-b38f-5d54ec820b95")
                });
            }
        }
    }
}
 

M.

1 użytkowników online, w tym zalogowanych: 0, gości: 1