0

I have researched a lot on how to get this working but I couldn't solve the problem, I also didn't like some of researched method because I believe it wastes Ram Space. Anyway, This is the problem:

I have two form: Form1(Has DataGridView(Modifier: Public), TextBox1, Button1) - Parent Form Form2(Has TextBox1, Button1) - Child Form

public partial class Form1 : Form
{
Pivate Void Button1_Click()
TransferText("Text_Example")

Public Void TransferText(string text)
Form2 frm2 = new Form2();
frm2.show()
frm2.textbox1 = text;
}

This obviously does not work, What is the correct way to do this ? I am trying to OPEN Form2, and change the textbox1 value of Form2.

On Form2, I have this code:

public partial class Form2 : Form
{
Private Void Button1_click()
RowAdder("Example-Text", "Example2");

Public Void RowAdder(string text1, string text2)
Form frm1 = ?? // What should I write here ?
frm1.DataGridView1.Rows.Add(text1, text2)

This also does not work, so how can I fix this ? I am trying to add rows on Form1, from Form2.

Any help on this issue is greatly appreciated. I have been stuck on this for awhile.

1
  • 2
    You can use a public property on Form2 that Form1 sets. In the Form2 property setter, use the passed value to update the text box. Jul 19, 2012 at 0:04

6 Answers 6

1

The Form class has a property called Owner of type Form and a method overload for show that sets this property. This allows you to pass a reference of your parent form to the child form.

You'll have to change your call to show to look like this:

form2.Show(this);

Then in your RowAdder method in form2 you'll have to cast the owner to a Form1 in order to access the datagridview there like this:

((Form1)Owner).DataGridView1.Rows.Add(text1, text2);

That will fix the problem of getting data from the child to parent form. Lots of people have already answered with the best way to get the data from the parent to the child so I'll just say read the other answers for that.

1
  • Perfect! Thank you for the help, and same goes for everyone else (:
    – e e
    Jul 19, 2012 at 1:29
1

Just create public property on your form2:

public string passtext;

on your Form1 just do:

   Form2 frm2 =  new Form2(){ passtext= "Text_Example"};
   frm2.Show();

On you Form2:

try this for test:

MessageBox.Show(passtext);

Regards

1
  • how would I send it from Form2, to Form1 ? To do the DataGridView.Rows.Add(Text, Text2) ?
    – e e
    Jul 19, 2012 at 0:31
1

Binding common data between views (forms) is something that has been addressed quite well in WPF, but with Winforms an approach I would suggest:

1) For Parent to Child transfers, create a public/internal property on the child which handles the mapping to the desired control. Better yet if there are going to be several fields/controls mapped, use something like a ViewModel: A class or struct that contains the relevant fields. For example: (using a string value) In Form2 (child)

public string ExampleText
{
   get { return exampleTextControl.Text; }
   set { exampleTextControl.Text = value; }
}

In Form 1 (parent)

form2.ExampleText = "fred";

A general rule is only expose the minimum amount of detail you need to. Back in VB, a "hack" was to make controls public so you could expose the entire textbox by setting a accessor property. You can do this in C#, but highly inadvisable.

2) For Child to Parent relationships: The cleanest option I can suggest is to adopt an event notification model. The child exposes an event which will provide details back for listening parents to consume. The parent form catches the event and performs its own updates.

Start with a simple event args declaration:

public class ExampleEventArgs : EventArgs
{
   public string Value1 
   {
      get;
      set;
   }
   public string Value2 
   {
      get;
      set;
   }
}

In the child form (Form2) create the event declaration:

public event EventHandler<ExampleEventArgs> OnRowAdded;

When you want to signal the parent to add a row:

if (OnRowAdded != null)
{
   OnRowAdded(this, new ExampleEventArgs { Value1 = text1, Value2 = text2 });
}

In the parent form (Form1) when your instance of Form2 is initialized you give it a method delegate to use for the OnRowAdded event handler. This can be a private method (VS can auto-generate this for you when you add the event handler) or you can use a Lambda expression:

var form2 = new Form2();
form2.OnRowAdded += (sender, e) => { this.DataGridView1.Rows.Add(e.Value1, e.Value2); };
// or form2.OnRowAdded += new EventHandler<ExampleEventArgs>( /* generate private method... */ );

*disclaimer: The above code is snippits from memory, it may not compile as-is, but should give you an idea of how to approach the problem.

0

To keep a good design of class, it is not recommended to expose the ID of a control within a form to the external. However, you can use C# Property or a designated public method to change a control.

0

You can change the ctor of Form2 to receive a string as argument and send it when you instantiate it.

Form2 form = new Form2(text);

On the ctor of Form2, you use that text

public Form2(string someText)
{
InitializeComponent();
//...
    this.textbox1.Text = someText;
//...
}

Regards

8
  • 1
    Don't forget to call base constructor. Jul 19, 2012 at 0:20
  • @SaniHuttunen actually you don't need to, but InitializeComponent is very important. Updated the answer, thanks Jul 19, 2012 at 0:29
  • 1
    Well... In the case that the only thing the constructor does is InitializeComponent then yes, you don't need to call the constructor. However this construction might change and therefor it is very important to call the constructor. From an architectural view you should never recreate the function of an existing constructor, you should use it. So I would NOT recommend to call only InitializeComponent, call the base constructor instead. More future safe and more architecturally correct. Jul 19, 2012 at 0:36
  • But the call of InitializeComponent is on the original ctor, removing it would change the behavior of the form. When you create a form, it comes with a parameterless ctor that calls InititalizeComponent. All I'm changing is the parameter, everything else is like the original. I don't believe that a future version of the framework would change this, because it would break all the Windows Applications developed on earlier versions, which is nonsense. Jul 19, 2012 at 0:52
  • Let's say someone finds a security flaw with System.Windows.Form and the solution is to call System.Windows.Forms.FixSecurity() in the ctor. This is added to .NET 7.5. Now... If you created an inherited class that DOESN'T call the ctor you have a big problem. You only call InitializeComponent. "OK. I'll just update my code then". You can't. Since you don't know which clients uses .NET 7.5 and which clients don't. This is a nightmare. If you only just had called the ctor then everyone who updated to .NET 7.5. would be safe. Jul 19, 2012 at 1:01
0

But it's a little bit messy Here is ùy suggestion!

Create a class to separate the this work from the UI :

public class YourController
{
    public DataGridView MyView { get; set; }

    //The method to add a row
    public void AddRowToView(string passedText)
    {
        using (Form2 f2 = new Form2())
        {
            if (f2.ShowDialog() == DialogResult.OK)
            {
                MyView.Rows.Add(passedText, f2.txEdit.Text);
            }
        }
    }
}

In your parent form, call the method to add the row :

//In your parent form, on the click button event :
YourController controller = new YourController() { MyView = view };
controller.AddRowToView("myText");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.