We help IT Professionals succeed at work.

winForm Controls over multiple Windows

mr-kenny
mr-kenny asked
on
I have a WinForms app with two windows (forms). In one is a dataGridView and i want to get the selected items in the other form.
How can I access the data in the other form?
Comment
Watch Question

Todd GerbertSenior Engineer
Top Expert 2010

Commented:
You can make the dataGridView public, and the second form would need a reference to the first form...e.g. you can pass a reference to Form1 into the constructor of Form2.
Senior Engineer
Top Expert 2010
Commented:
Crude example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
	public class Form1 : Form
	{
		public TextBox TextBox1;

		public Form1()
		{
			FlowLayoutPanel flp = new FlowLayoutPanel();

			TextBox1 = new TextBox();
			flp.Controls.Add(TextBox1);

			Button btn = new Button();
			btn.Text = "Open 2nd Form";
			btn.AutoSize = true;
			btn.Click += new EventHandler(btn_Click);
			flp.Controls.Add(btn);

			this.Controls.Add(flp);
		}

		void btn_Click(object sender, EventArgs e)
		{
			new Form2(this).Show();
		}
	}

	public class Form2 : Form
	{
		private Form1 _Form1;
		private Label lbl;

		public Form2(Form1 opener)
		{
			_Form1 = opener;

			FlowLayoutPanel flp = new FlowLayoutPanel();

			lbl = new Label();
			lbl.Text = "Text from form1 text box: ";
			lbl.AutoSize = true;
			flp.Controls.Add(lbl);

			Button btn = new Button();
			btn.Text = "Get Text From Form1";
			btn.AutoSize = true;
			btn.Click += new EventHandler(btn_Click);
			flp.Controls.Add(btn);

			this.Controls.Add(flp);
		}

		void btn_Click(object sender, EventArgs e)
		{
			lbl.Text = "Text from form1 text box: " + _Form1.TextBox1.Text;
		}
	}
}

Open in new window

Author

Commented:
thanks