Data fall from one form to another

I have a grid form, and I want to transfer information from the first form to the second based on which row is selected when the user clicks the edit button.

What is the best way? and how should I decide how the form should be empty if the user wants to add a new one or fill out the second (right) form with the values ​​from the selected row of the first datagrid type? String values ​​are all properties of the same object.

I can delete and add a new object, its editing an existing one, which is difficult for me to work with, and how can I load the second form?

I am currently creating an instance and an instance of instance.Show ();

This works by opening a blank form, but I want to load it with an object based on the selected line when the user wants to edit an existing entry.

+4
source share
2 answers

Let's say your form1 is a form with a data grid (grdMyData) that displays rows of instances of the MyClass class, and form2 is a form for editing the data of this row. When the user clicks "Edit", you can use this:

private void btnEdit_Click(sender e, EventArgs arg) { if (grdMyData.SelectedRows.Count == 0) return; //nothing to do MyClass selectedRow = (MyClass)grdMyData.SelectedRows[0].DataBoundItem; Form2 frm2 = new Form2(selectedRow); if (frm2.ShowDialog() == DialogResult.OK) { //do something if needed } } 

This code assumes that you have your own Form2 constructor that accepts the type of object it works with. At the same time, when you work in Form2, the data automatically affects the display of Form1, because they work with an instance of the same object.

+1
source

I would suggest exposing an event in one form that another form can use.

Here is the official tutorial
http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

Basically it would be something like this

 // Source form public event YourEventHandlerType EventName; // Wherever the event occurs EventName.Invoke(...); // Destination form this.referenceToSourceForm.EventName += MyEventHandler(...); 

So, you will need some reference to the source form in the destination form, or you will need to configure event handling outside of the two forms.

0
source

Source: https://habr.com/ru/post/1299865/


All Articles