Reputation: 512
I have a form with a grid and I want to pass info from the first form to 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 blank if the the user wants to add a new or fill the second(edit) form with the values from the selected row of the first forms datagrid? The row values are all properties of the same object.
I can delete and add a new object, its editing an exsisting one that I am having a hard time with, and how should I load the second form?
I am currently creating and instance then instance.Show();
This is working the open a blank form, but I want to loadd it with the object based on the selected row when the user wants to edit an exsisting record.
Upvotes: 4
Views: 227
Reputation: 8514
Let's say your form1 is the form with data grid (grdMyData) that's displaying rows of MyClass class instances, and form2 is the form for editing the data of the given row. When user clicks Edit, you could 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 is assuming you have the proper Form2 constructor which takes the type of object it works with. With this when you are working in Form2 the data will automatically affect the Form1 display because they're working with the instance of the same object.
Upvotes: 1
Reputation: 13497
I would suggest exposing an event in one form that the other form can consume.
Here is the offical 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 setup the event handling outside of the two forms otherwise.
Upvotes: 0