-1

I am trying to take the value of a cell from a selected row in my form 1 datagridview. I want to store this value in a variable so I can update specific entries my database with the appropriate ID using said variable.

I have already set the datagridview to public in properties but for some reason it still wont recognize the datagrid on my other form. My code looks like this on Form 2:

                   var selectedAppointmentId = appointmentDgv.CurrentRow.Cells[0].Value;

                   Appointment appointment = new Appointment();
                   appointment.AppointmentID = int.Parse((string)selectedAppointmentId);

This code is located in an edit button so that I might make changes to the database. I keep getting the error: "The name 'appointmentDgv' does not exist in current context". I am relatively new to C#.

  • Does this answer your question? [Communicate between two windows forms in C#](https://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp) – JohnG Nov 18 '21 at 11:27

1 Answers1

0

Consider loading data for the DataGridView into a DataTable (or a List of T) which is assigned to a BindingSource, the BindingSource is set to the DataSource of the DataGridView.

Subscribe to PositionChanged event of the BindingSource.

Setup a property in the form with the DataGridView e.g. to get say the primary key. Since the setter is private the value can only be changed in the child form, not the calling form so it's protected.

public int CurrentIdentifier { get; private set; }

In PositionChanged event of the BindingSource get the value you need, in this case a primary key from a DataRow. Here the BindingSource name is _customerBindingSource.

if (_customerBindingSource.Current == null)
{
    CurrentIdentifier = -1;
}
CurrentIdentifier = (_customerBindingSource.Current as DataRowView).Row.Field<int>("Id");

In the form which needs the value create a private property for the form above then to get the value, Id in this case.

if (_childForm.CurrentIdentifier > -1)
{
    var appointment = new Appointment { AppointmentID = _childForm.CurrentIdentifier };
}
else
{
    // no current row
}

By using a BindingSource you never need to touch cells in a DataGridView, data is strongly typed. Also, there are many benefits to a BindingSource which you should take time to explore.

Karen Payne
  • 4,341
  • 2
  • 14
  • 31