C# textbox sending text value. Situation, i got 2 forms. Form1 and Form2. Form1 got a textbox and form2 got a textbox and a button, i will put a text value on form2 textbox and when i click the form2 button the value of form2 textbox will be sent and change the form1 textbox value....Need help..
This is what ive done..im just gonna summarize it
Form1 got no codes just textbox1
This is the code in form2 button
private void change_Click(object sender, EventArgs e)
{
form1 frm1 = new form();
string test = textbox2.text
frm1.textbox.text = test;
}
ive try some poping message box to check if the value pass...and so far the value was really pass but no changes in the UI
Assuming you create Form2 as a child of Form1 (from within Form1, do something like Form2 from = new Form2();, you can access any public property of the child form from within the parent. So, just make sure to set the accessibility of the TextBox to public, and do something like this:
var form = new Form2();
form.ShowDialog();
this.TextBox1.Text = form.TextBox1.Text;
You can declare the textbox in Form1 to be public, then you can access it from form2 by going form1.textBoxName.propertyName
You could use events for this:
Define an interface:
public interface ITextChange
{
event EventHandler SomeTextChanged;
}
Then let you form with button implement this interface and fire the event on button click passing the value from the textbox as the first parameter:
public partial class Form1 : Form, ITextChange
{
public event EventHandler SomeTextChanged = delegate { };
public Form1 () {}
private void button1_Click(object sender, EventArgs e)
{
SomeTextChanged(textBox1.Text, null);
}
}
Pass an instance of this form to your second form like this:
public partial class Form2 : Form
{
public Form2(ITextChange f)
{
InitializeComponent();
f.SomeTextChanged += new EventHandler(f_SomeTextChanged);
}
void f_SomeTextChanged(object sender, EventArgs e)
{
textBox1.Text = sender.ToString();
}
}
So, when you create your Form2, you need to pass an instanse of Form1:
Form2 f = new Form2(form1);
As soon as you press the button, the textbox on the second form will automatically get the value.
P.S.: for more info, please, see Events Tutorial
You could rely on knowledge of Form1 in Form2 by making the TextBox public. But in my opinion the proper way to do it would to create a custom event handler, subscribe to it in Form2 and pass the text as a eventarg. Code adapted from this MSDN Article
Form1
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form2 frm2 = new Form2();
frm2.RaiseCustomEvent+=new CustomEventHandler(frm2_RaiseCustomEvent);
frm2.Show(this);
}
void frm2_RaiseCustomEvent(object sender, CustomEventArgs a)
{
textBox1.Text = a.Message;
}
}
}
Form2
namespace WindowsFormsApplication1
{
public delegate void CustomEventHandler(object sender, CustomEventArgs a);
public partial class Form2 : Form
{
public event CustomEventHandler RaiseCustomEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RaiseCustomEvent(this, new CustomEventArgs(textBox1.Text));
}
}
public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
msg = s;
}
private string msg;
public string Message
{
get { return msg; }
}
}
}
you could use the .Tag property (look at my question here
the simple way to do it is like this:
you said that the textBox.text in form2 would replace the texBox.text in form1 right?
do this in the form2
try
{
private void change_Click(object sender, EventArgs e)
{
form2 frm2 = new form();
frm2.Tag = this.textbox2.text;
frm2.ShowDialog();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
then write this when you load your form1
string myText = (string)this.Tag;
this.textbox1.text = myText;
The reason your form1.textbox1 was not updated because you initialized a new instance of form1
form1 frm1 = new form();
So to update the form1 you have on screen, you need to get its instance injected into the form2. For instance, when you show form2, you set.
form2.Form1 = currentForm1Instance;
Hope this helps.
Related
I have 2 forms.
On form1 there is a textbox called textbox1 and a button [and many other textboxes as well]
On clicking the button , a new form , form2 opens
form 2 has a datagridview with 2 columns.
On clicking the datagridview cell [present in form2]
Using :
private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
,
The contents of the first column of the selected row must go to the textbox1 in form1 , without refreshing or reopening form1 .
How do I do that without using the .show() method as it would refresh my form1 and as a result lose all the user-typed info in the other textboxes?
Note: retrieval from datagridview to string form is done by:
dataGridView.SelectedRows[0].Cells[1].Value.ToString()
Put that cell value in a public property like
public string gridcellValue
{
get; set;
}
In your dataGridView_CellMouseClick( event handler set the property saying
this.gridcellValue = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
Then in your form1 you can access it using the instance of form2 (since you created the form2 instance from form1)
textbox1.Text = frm2.gridcellValue;
Another approach is make that textbox a public property and pass the form1 instance in form2 constructor and set the textbox like
In Form1
public TextBox Form1Text
{
get {return this.testbox1;}
set {this.testbox1 = value;}
}
Form2 frm2 = new Form2(this);
frm2.Show();
In Form2
public class Form2 : Form
{
Form _form1;
public Form2(Form1 frm)
{
_form1 = frm;
}
//In event handler
private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
//set the value
((TextBox)_form1.Form1Text).Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
}
}
I solved it and I think my answer could help someone in need[like I was]
Basically , in Form1 , you create a public static string ,like
public static string mystring = "";
then on the button which leads you to Form2 , do the following:
private void button_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
if (frm.ShowDialog() == DialogResult.OK)
{
this.txt_box.Text = Form1.mystring;
}
}
`
In form2,:
`
private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
Form1.mystring = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
this.DialogResult = DialogResult.OK;
this.Close();
}
And that is it!
good luck
I have two forms. First, Form1 has a group box, some labels and a listbox. I press a button and new Form2 is opened and contains some text. I want to transfer the text in Form2 to the listbox in the Form1.
So far, what I have done is make modifier of listbox to public and then put this code in the button of Form2
Form1 frm = new Form1();
frm.ListBox.items.Add(textBox.Text);
But amazingly, this does not add any value. I thought I was mistaken with the insertion so I made the same procedure. This time, I made a label public and added textbox value to its Text property but it failed.
Any ideas?
Try adding a parameter to the constructor of the second form (in your example, Form1) and passing the value that way. Once InitializeComponent() is called you can then add the parameter to the listbox as a choice.
public Form1(String customItem)
{
InitializeComponent();
this.myListBox.Items.Add(customItem);
}
// In the original form's code:
Form1 frm = new Form1(this.textBox.Text);
Let's assume Form1 calls Form2. Please look at the code:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
frm.VisibleChanged += formVisibleChanged;
}
private void formVisibleChanged(object sender, EventArgs e)
{
Form2 frm = (Form2)sender;
if (!frm.Visible)
{
this.listBox1.Items.Add(frm.ReturnText);
frm.Dispose();
}
}
}
Form2:
public partial class Form2 : Form
{
public string ReturnText { get; set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.ReturnText = this.textBox1.Text;
this.Visible = false;
}
}
The answer is to declare public property on Form2 and when form gets hidden. Access the same instance and retrieve the value.
Below code working perfect on my machine.
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.listBox1.Items.Add(textBox1.Text );//ListBox1 : Modifier property made public
f1.ShowDialog();
}
Ok, If you are Calling Sequence is like, Form1->Form2 and Form2 updates the value of Form1 then you have to use ParentForm() or Delegate to update the previous form.
Form1 frm = new Form1();
frm is now a new instance of class Form1.
frm does not refer to the original instance of Form1 that was displayed to the user.
One solution is, when creating the instance of Form2, pass it a reference to your current instance of Form1.
Please avoid the concept of making any public members like you said
>>i have done is make modifier of listbox to public and then in form2 in button code<<
this is not a good practice,on the other hand the good one is in Brad Christie's Post,I hope you got it.
This code will be inside the form containing myListBox probably inside a button click handler.
Form2 frm2 = new Form2();
frm2.ShowDialog();
this.myListBox.Items.Add(frm2.myTextBox.Text);
frm2.Dispose();
I want to pass values between two Forms (c#). How can I do it?
I have two forms: Form1 and Form2.
Form1 contains one button. When I click on that button, Form2 should open and Form1 should be in inactive mode (i.e not selectable).
Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.
How can i do it? Can somebody help me to do this with a simple example.
There are several solutions to this but this is the pattern I tend to use.
// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
if(form2.ShowDialog() == DialogResult.OK)
{
someControlOnForm1.Text = form2.TheValue;
}
}
And...
// Inside Form2
// Create a public property to serve the value
public string TheValue
{
get { return someTextBoxOnForm2.Text; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
}
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
Define a property
public static class ControlID {
public static string TextData { get; set; }
}
In the Form1
private void button1_Click(object sender, EventArgs e)
{
ControlID.TextData = txtTextData.Text;
}
Getting the data in Form1 and Form2
private void button1_Click(object sender, EventArgs e)
{
string text= ControlID.TextData;
}
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as public static datatype 'variableName' in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.
Example of such is,
Form1
public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass
Form2
TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2
Declare a public string in form1
public string getdata;
In button of form1
form2 frm= new form2();
this.hide();
form2.show();
To send data to form1 you can try any event and code following in that event
form1 frm= new form1();
form1.getdata="some string to be sent to form1";
Now after closing of form2 and opening of form1, you can use returned data in getdata string.
I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.
I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications
Form1 Code :
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}
Form2 Code :
public Form2()
{
InitializeComponent();
t = textBox1; //Initialize with static textbox
}
public static TextBox t=new TextBox(); //make static to get the same value as inserted
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
It Works!
declare string in form1
public string TextBoxString;
in form1 click event add
private void button1_Click(object sender, EventArgs e)
{
Form1 newform = new Form1();
newform = this;
this.Hide();
MySecform = new Form2(ref newform);
MySecform.Show();
}
in form2 constructer
public Form2(ref Form1 form1handel)
{
firstformRef = form1handel;
InitializeComponent();
}
in form2 crate variable Form1 firstformRef;
private void Submitt_Click(object sender, EventArgs e)
{
firstformRef.TextBoxString = textBox1.Text;
this.Close();
firstformRef.Show();
}
In this code, you pass a text to Form2. Form2 shows that text in textBox1.
User types new text into textBox1 and presses the submit button.
Form1 grabs that text and shows it in a textbox on Form1.
public class Form2 : Form
{
private string oldText;
public Form2(string newText):this()
{
oldText = newText;
btnSubmit.DialogResult = DialogResult.OK;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = oldText;
}
public string getText()
{
return textBox1.Text;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
}
And this is Form1 code:
public class Form1:Form
{
using (Form2 dialogForm = new Form2("old text to show in Form2"))
{
DialogResult dr = dialogForm.ShowDialog(this);
if (dr == DialogResult.OK)
{
tbSubmittedText = dialogForm.getText();
}
dialogForm.Close();
}
}
Ok so Form1 has a textbox, first of all you have to set this Form1 textbox to public in textbox property.
Code Form1:
Public button1_click()
{
Form2 secondForm = new Form2(this);
secondForm.Show();
}
Pass Form1 as this in the constructor.
Code Form2:
Private Form1 _firstForm;
Public Form2(Form1 firstForm)
{
_firstForm = firstForm:
}
Public button_click()
{
_firstForm.textBox.text=label1.text;
This.Close();
}
you can pass as parameter the textbox of the Form1, like this:
On Form 1 buttom handler:
private void button2_Click(object sender, EventArgs e)
{
Form2 newWindow = new Form2(textBoxForReturnValue);
newWindow.Show();
}
On the Form 2
public static TextBox textBox2; // class atribute
public Form2(TextBox textBoxForReturnValue)
{
textBox2= textBoxForReturnValue;
}
private void btnClose_Click(object sender, EventArgs e)
{
textBox2.Text = dataGridView1.CurrentCell.Value.ToString().Trim();
this.Close();
}
Constructors are the best ways to pass data between forms or Gui Objects you can do this.
In the form1 click button you should have:
Form1.Enable = false;
Form2 f = new Form2();
f.ShowDialog();
In form 2, when the user clicks the button it should have a code like this or similar:
this.Close();
Form1 form = new Form1(textBox1.Text)
form.Show();
Once inside the form load of form 1 you can add code to do anything as you get the values from constructor.
How to pass the values from form to another form
1.) Goto Form2 then Double click it. At the code type this.
public Form2(string v)
{
InitializeComponent();
textBox1.Text = v;
}
2.) Goto Form1 then Double click it. At the code type this.
//At your command button in Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 F2 = new Form2(textBox1.Text);
F2.Show();
}
This is very simple.
suppose you have 2 window form Form1 and Form2 and you want to send record of textbox1 from Form1 to Form2 and display this record in label1 of Form2;
then in Form2 create a label which name is label1 and go to the property of label1 and set 'Modifiers'=public and in Form one create a textBox with id textBox1 and a button of name submit then write the following code on button click event
button1_Click(object sender, EventArgs e)
{
Form2 obj=new Form2();
obj.label1.text=textBox1.text.ToString();
obj.show();
}
thats it...
for this way you can bind dataset record to another form's datagridview......
You can make use of a different approach if you like.
Using System.Action (Here you simply pass the main forms function as the parameter to the child form like a callback function)
OpenForms Method ( You directly call one of your open forms)
Using System.Action
You can think of it as a callback function passed to the child form.
// -------- IN THE MAIN FORM --------
// CALLING THE CHILD FORM IN YOUR CODE LOOKS LIKE THIS
Options frmOptions = new Options(UpdateSettings);
frmOptions.Show();
// YOUR FUNCTION IN THE MAIN FORM TO BE EXECUTED
public void UpdateSettings(string data)
{
// DO YOUR STUFF HERE
}
// -------- IN THE CHILD FORM --------
Action<string> UpdateSettings = null;
// IN THE CHILD FORMS CONSTRUCTOR
public Options(Action<string> UpdateSettings)
{
InitializeComponent();
this.UpdateSettings = UpdateSettings;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
// CALLING THE CALLBACK FUNCTION
if (UpdateSettings != null)
UpdateSettings("some data");
}
OpenForms Method
This method is easy (2 lines). But only works with forms that are open.
All you need to do is add these two lines where ever you want to pass some data.
Main frmMain = (Main)Application.OpenForms["Main"];
frmMain.UpdateSettings("Some data");
I provided my answer to a similar question here
You can use this;
Form1 button1 click
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
this.Hide();
frm2.Show();
}
And add this to Form2
public string info = "";
Form2 button1 click
private void button1_Click(object sender, EventArgs e)
{
info = textBox1.Text;
this.Hide();
BeginInvoke(new MethodInvoker(() =>
{
Gogo();
}));
}
public void Gogo()
{
Form1 frm = new Form1();
frm.Show();
frm.Text = info;
}
if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control.
f.e. :
Form2 frm;
private void Form1_Load(object sender, EventArgs e)
{
frm = new Form2();
frm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(frm.txtUserName.Text);
//txtUserName is a TextBox with Modifiers=Public
}
// In form 1
public static string Username = Me;
// In form 2's load block
string _UserName = Form1.Username;
the tag Properties receive object value
( C# send value to another form )
private void btn_Send_Click(object sender, EventArgs e)
{
Form frm = new formToSend();
frm.tag = obj;
frm.ShowDialog();
}
Receive value that sent from previous form ( frm )
Ex: sent data is string ( we need to type casting first, because tag value is an object )
public Receive_Form()
{
InitializeComponent();
MessageBox.Show((string)this.Tag);
}
How about using a public Event
I would do it like this.
public class Form2
{
public event Action<string> SomethingCompleted;
private void Submit_Click(object sender, EventArgs e)
{
SomethingCompleted?.Invoke(txtData.Text);
this.Close();
}
}
and call it from Form1 like this.
private void btnOpenForm2_Click(object sender, EventArgs e)
{
using (var frm = new Form2())
{
frm.SomethingCompleted += text => {
this.txtData.Text = text;
};
frm.ShowDialog();
}
}
Then, Form1 could get a text from Form2 when Form2 is closed
Thank you.
I have 2 forms which consist of:
Form1:
2buttons named:
btnCopy and
btnPaste
(with functions inside like rtb.Copy(); and rtb.Paste(); that should work for richtextbox in Form2)
Form2:
1richtextbox named: rtb
My question was:
How can I communicate between the 2buttons from Form1 (with its functions) and the richtextbox in Form2.
like: When I type text inside richtextbox(rtb) in Form2 then i SelectAll text then I Press the CopyButton(btnCopy) from Form1, text should be copied same as when I Press PasteButton(btnPaste) from Form1, text that has been copied should be Paste in RichTextBox(rtb) that could be Found on Form2 .
How can I do that?
Let's say you have Form1 and ToolStrip Button name PasteToolStripButton like:
public partial class Form1 : Form
{
Form2 formChild;
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
formChild = new Form2();
formChild.MdiParent = this;
formChild.Show();
}
private void CopyToolStripButton_Click(object sender, EventArgs e)
{
formChild.CopyText(); // Method to copy Rich Text Box in Form2
}
private void PasteToolStripButton_Click(object sender, EventArgs e)
{
formChild.PasteText(); // Method in Form2 to Paste to the RichTextBox in Form2
}
}
In your Form2 you need to add a Public method named PasteText and CopyText like:
public void PasteText()
{
rtbChild.Text = Clipboard.GetText(); // this one simulates the rtb.Paste()
}
public void CopyText()
{
rtb.Copy();
}
I also named the RichTextBox in Form2 as rtbChild so every time you click for example paste in will be copied in your RichTextBox in Form2.
Create a public property on Form1 then set it from Form2.
EDIT:
On Form1:
public string TextForRTB {get; set;}
On Form2:
Form1 a = new Form1();
a.TextForRtb = rtb.Text;
Sol1: Pass one of the forms to the other, as Form1(Form parent){....} in the constructor, then you should see it's public properties and methods.
Sol2: Create custom events to raise it when text changed on your rich text box, so than the forms that initialized the form with this rich box will do something, like enable/disable a button or something
...Actually, there is a lot of solutions to this kind of behavior, and I wonder why you need to put your text box in a different form from your buttons that seems to be related very closely in business logic together!
You could expose 2 methods GetRichTextBoxContent and SetRichTextBoxContent in Form2.
Which would update the contents of richTextBox in Form2.
Then you could work on the Instance of Form2 form Form1
Note: The major think here is how you get the Instance of Form2. It is up to your implementation to get that instance.
public class Form2 : Form
{
public string GetRichTextBoxContent()
{
return this.richTextBox1.Text;
}
public void SetRichTextBoxContent(string content)
{
this.richTextBox1.Text = content;
}
}
public class Form1 : Form
{
//Based on your implementation
Form2 form2 = new Form2();
private void Button_CopyClick(object sender, EventArgs e)
{
var contentFromRtb = form2.GetRichTextBoxContent();
}
private void Button_PasteClick(object sender, EventArgs e)
{
var someContent = "Content to be copied to text box"
form2.SetRichTextBoxContent(someContent );
}
}
I have two Form classes, one of which has a ListBox. I need a setter for the SelectedIndex property of the ListBox, which I want to call from the second Form.
At the moment I am doing the following:
Form 1
public int MyListBoxSelectedIndex
{
set { lsbMyList.SelectedIndex = value; }
}
Form 2
private ControlForm mainForm; // form 1
public AddNewObjForm()
{
InitializeComponent();
mainForm = new ControlForm();
}
public void SomeMethod()
{
mainForm.MyListBoxSelectedIndex = -1;
}
Is this the best way to do this?
Making them Singleton is not a completely bad idea, but personally I would not prefer to do it that way. I'd rather pass the reference of one to another form. Here's an example.
Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.
With this approach you can do communication in different ways.
Download Link for Sample Project
//Your Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
public string LabelText
{
get { return Lbl.Text; }
set { Lbl.Text = value; }
}
}
//Your Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private Form1 mainForm = null;
public Form2(Form callingForm)
{
mainForm = callingForm as Form1;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.mainForm.LabelText = txtMessage.Text;
}
}
(source: ruchitsurati.net)
(source: ruchitsurati.net)
Access the form's controls like this:
formname.controls[Index]
You can cast as appropriate control type, Example:
DataGridView dgv = (DataGridView) formname.Controls[Index];
I usually use the Singleton Design Pattern for something like this http://en.wikipedia.org/wiki/Singleton_pattern . I'll make the main form that the application is running under the singleton, and then create accessors to forms and controls I want to touch in other areas. The other forms can then either get a pointer to the control they want to modify, or the data in the main part of the application they wish to change.
Another approach is to setup events on the different forms for communicating, and use the main form as a hub of sorts to pass the event messages from one form to another within the application.
It's easy, first you can access the other form like this:
(let's say your other form is Form2)
//in Form 1
Form2 F2 = new Form2();
foreach (Control c in F2.Controls)
if(c.Name == "TextBox1")
c.Text = "hello from Form1";
That's it, you just write in TextBox1 in Form2 from Form1.
If ChildForm wants to access the ParentForm
Pass ParentForm instance to the ChildForm constructor.
public partial class ParentForm: Form
{
public ParentForm()
{
InitializeComponent();
}
public string ParentProperty{get;set;}
private void CreateChild()
{
var childForm = new ChildForm(this);
childForm.Show();
}
}
public partial class ChildForm : Form
{
private ParentForm parentForm;
public ChildForm(ParentForm parent)
{
InitializeComponent();
parentForm = parent;
parentForm.ParentProperty = "Value from Child";
}
}
There is one more way, in case you don't want to loop through "ALL" controls like Joe Dabones suggested.
Make a function in Form2 and call it from Form1.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void SetIndex(int value)
{
lsbMyList.SelectedIndex = value;
}
}
public partial class Form1 : Form
{
public Form2 frm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
frm=new Form2();
frm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
frm.SetIndex(Int.Parse(textBox1.Text));
}
}
Here's also another example that does "Find and Highlight". There's a second form (a modal) that opens and contains a textbox to enter some text and then our program finds and highlights the searched text in the RichTextBox (in the calling form). In order to select the RichTextBox element in the calling form, we can use the .Controls.OfType<T>() method:
private void findHltBtn_Click(object sender, EventArgs e)
{
var StrBox = _callingForm.Controls.OfType<RichTextBox>().First(ctrl => ctrl.Name == "richTextBox1");
StrBox.SelectionBackColor = Color.White;
var SearchStr = findTxtBox.Text;
int SearchStrLoc = StrBox.Find(SearchStr);
StrBox.Select(SearchStrLoc, SearchStr.Length);
StrBox.SelectionBackColor = Color.Yellow;
}
Also in the same class (modal's form), to access the calling form use the technique mentioned in the #CuiousGeek's answer:
public partial class FindHltModalForm : Form
{
private Form2 _callingForm = null;
public FindHltModalForm()
{
InitializeComponent();
}
public FindHltModalForm(Form2 CallingForm)
{
_callingForm = CallingForm;
InitializeComponent();
}
//...