1
votes

I have 2 form Form1 and Form2, I want to update datagridview in Form1 from Form2 first i select the row of datagridview in Form1 then click a button to open Form2. in Form2 I input the new data then save it.

how I can do that?

2

2 Answers

-1
votes

You can make a public method on Form1 to insert the row. Let's call it LoadData. This would receive a set of parameters indicative of the data on Form2.

public void LoadData( ... )
{
    // load the data into the data grid
}

Then add a new constructor to Form2:

public Form2(Form1 referrer)
{
    _referrer = referrer;
}

where _referrer is a private field typed as Form1:

private Form1 _referrer;

Then when you load Form2, pass in this because you're on Form1:

var f = new Form2(this);

Finally, when you want to add the data from Form2, do this:

_referrer.LoadData( ... );
-1
votes

My solution is similar to @Michael Perrenoud's. Your purpose is to pass value from form1 to form2. How to pass? usually you need to pass the object in form1 to form2 by constructor of form2. then, what to pass? others say pass the form1 itself or pass the gridview control, but I prefer to pass the data you really want to use in form2, why? because when you pass a control(form or gridview), you need to analyse and get the data with it, then add to gridview2 in form2, think about that, when you pass control from form1, maybe one day you will replace the gridview by other controls such as listview or treeview, evenmore, that one day you may abandon form1, so you need to modify and Refactor your form2. but if you pass the data only, you can reuse the form2. here is my sample code:

first, add a private field refering to your passed data

private object mydata = null;

add a function to fill the gridview with the passed data

public void FillData( ... )
{
    if(mydata != null)
    {
    //add the data into gridview
     }
}

then, add a new constructor to Form2:

public Form2(object data)
{
    _mydata = data;
}

when you want to show form2, please get the data from gridview1

void ShowData()
{
     object mydata = null;
     //get the data from selected rows and set to mydata
     Form2 f = new Form2(mydata);
     f.ShowDialog();
}