Home > OS >  Save DataGridView row to class object
Save DataGridView row to class object

Time:10-29

I want to save one (or more) rows of a datagridview.

For that I have a class Person

public class Person
    {
        public string Name;
        public string FirstName;
        public DateTime DateOfBirth;
        int DateOfBirth()
    }

If I open the Form I want an emtpy datagridview but with the columns of the class and an empty row. So that the user can add the data directly in the dataGridView.

Now my question how to do that?

If I do something like this

List<Person> myList = new List<Person>();
dataGridView1.DataSource = myList;

then I can't add data in the datagridview cause it is bound.

And what is an elegant way to save the entered data to the database as an object list?

I tried to add the columns manually like and to save using a for or foreach loop that looks like that `

...
                    // Name
                    if (dataGridView1[2, i].Value == null)
                    {
                        person.Name = "";
                    }
                    else
                    {
                        person.Name = dataGridView1[2, i].Value.ToString();
                    }
...

` And I think that this is not the good way ...

CodePudding user response:

Create columns in the DataGridView, set the dataPropertyName for each property in your class that will be displayed.

Setup a BindingList of Person, setup a BindingSource and assign the BindingSource to the DataGridView DataSource.

The following is setup as per above, the user can add a record directly in the DataGridView of using a button.

There is no reason to acccess data other than through the components.

namespace FrontendApplication
{
    public partial class Form4 : Form
    {
        private readonly BindingSource _bindingSource = new();
        private BindingList<Person> _peopleLocalList;
        public Form4()
        {
            InitializeComponent();

            dataGridView1.AutoGenerateColumns = false;
            _peopleLocalList = new BindingList<Person>();

            _bindingSource.DataSource = _peopleLocalList;
            dataGridView1.DataSource = _bindingSource;
        }

        private void CurrentButton_Click(object sender, EventArgs e)
        {
            if (_bindingSource.Current is null) return;
            Person person = _peopleLocalList[_bindingSource.Position];
            MessageBox.Show($"{person.FirstName} {person.LastName}");
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            var test = _peopleLocalList.FirstOrDefault(p => p.Id == 3);
            if (test is null)
            {
                _peopleLocalList.Add(new Person()
                {
                    Id = 3, FirstName = "Karen", LastName = "Payne"
                });
            }
        }
    }
}

Sample Person class I had already

public class Person : INotifyPropertyChanged
{
    private string _firstName;
    private string _lastName;
    public int Id { get; set; }

    public string FirstName
    {
        get => _firstName;
        set
        {
            _firstName = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(FullName));
        }
    }

    public string LastName
    {
        get => _lastName;
        set
        {
            _lastName = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(FullName));
        }
    }

    public string FullName => $"{FirstName} {LastName}";

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Edit the current row in the DataGridView

private void EditButton_Click(object sender, EventArgs e)
{
    if (_bindingSource.Current is null) return;
    Person person = _peopleLocalList[_bindingSource.Position];
    person.FirstName = "Anne";
    person.LastName = "Payne";
}

Or

private void EditButton_Click(object sender, EventArgs e)
{
    var person = _peopleLocalList.FirstOrDefault(p => p.Id == 3);
    if (person is not null)
    {
        person.FirstName = "Jane";
    }
}
  • Related