I want to access the list box and add the item into it for my Custom control which is dynamically created on run time. I want to add the Item when I press the button place in the custom control, but it does not work. I have use the following code to work:
private void button1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ABC = "HI";
}
the 'ABC' is the Public string on the form ie:
public string ABC
{
set { listBox1.Items.Add (value); }
}
the above string works fine when I use it form the Button on the form and it adds the value in the lsitbox but whent I use it form the custom control's button the text of the 'value' changes but it does not add the item in list box.I have also try it on tabel but does not help. I change the Modifires of the ListBox1 from Private to Public but it does not works. The above function works well in the form but cannot work from the custom control.
Thanks.
Expose an event ("ItemAdded" or whatever) in the child form that your main form can handle. Pass the data to any event subscribers through an EventArgs derived object. Now your mainform can update the UI as it please with no tight coupling between the two classes. One class should not know about the UI layout of another, it's a bad habit to get into (one that everyone seems to suggest when this question crops up).
What I think you should use is
this.ParentForm
So in your case it should be:
public string ABC
{
set { this.ParentForm.listBox1.Items.Add (value); }
}
The easiest way would be to pass the form down into your custom control as a parameter in the constructor that way you could access it from the custom control.
EX:
public class CustomControl
{
private Form1 _form;
public CustomControl(Form1 form)
{
_form = form;
}
private void button1_Click(object sender, EventArgs e)
{
_form.ABC = "HI";
}
}
Related
I have a main form (form1) which has a panel (panel1) -- see pic.
Form1 pic
Panel1 loads one of two different user controls based on which button is pressed (to simulate screen changes). I have a button on user control 1 which needs to act (change text) on user control 2.
The issue I have is the user controls are dynamically created with a button press on form 1 (see code below) which is causing me issues trying to link events-
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.Controls.Add(new Screens.UC1());
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new Screens.UC1());
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new Screens.UC2());
}
}
What is the best way to deal with linking these kinds of items with events when the instance of the objects are dynamically created. I also tried making instances of the screen and then referencing to those, but that ran into scope issues.
Code for UC1 (user control 1)
public partial class UC1 : UserControl
{
public UC1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Event to change text on UC2
}
}
Code for UC2 (user control 2)
public partial class UC2 : UserControl
{
public UC2()
{
InitializeComponent();
}
public void WriteText(object sender, EventArgs e)
{
label2.Text = "Text Changed...";
}
}
Any help greatly appreciated.
Why dispose and create all those controls when the operator presses a button?
Better is to create two UserControls. One with all the Controls you want to show when operator presses button 1 and one with all the Controls you want to show when operator presses button 2.
To create a user control use menu Project - Add User Control, or right click in solution explorer on your project and select add new item.
Layout your user controls with all the controls your want to show. Add event handlers etc.
Then in your form:
private readonly UserControl userControl!;
private readonly UserControl userControl2;
public MyForm()
{
InitializeComponent()
this.userControl1 = new UserControlA(...);
this.userControl2 = new UserControlB(...);
// make sure that the user controls are Disposed when this form is Disposed:
this.Components.Add(this.userControl1);
this.Components.Add(this.userControl2);
}
void OnButton1Clicked(object sender, ...)
{
// remove userControl2 from the panel
this.Panel1.Controls.Remove(this.userControl2);
// add userControl1 to the panel
this.Panel1.Controls.Add(this.userControl1);
}
This way all the overhead of creating / adding / positioning / add event handlers and all cleanup is only done once: during construction of your form. Switching the user controls will be done in a flash
I am not sure what you are trying to accomplish, but it looks like you are trying to change the state of objects from other objects that cannot have references to the objects they are trying to change.
In this case, I would create a type that functions as some kind of manager that subscribes to events of all of these controls. You can create your own events within a UC class, or just use the Windows Forms click event like you are already doing.
Since the handler of the events are defined in the manager, you can easily write logic that will work on the other user controls, as long as the manager has references to them.
Like this:
public class ClickTrafficer {
private UC target;
public void HandleClick(object sender, UCClickHandlerEventArgs ea) {
target.WriteText(ea.TextToWrite);
}
}
public Form1()
{
InitializeComponent();
var trafficer = new ClickTrafficer();
var screen1 = new Screens.UC1();
screen1.Click += trafficer.HandleClick;
panel1.Controls.Add(screen1);
}
This is a crude idea of what you could do. Missing here are the logic to set whatever the target field must be set to. You need to create logic that tells the trafficer which control sets which control's text.
Also, the ClickTrafficer I created uses a custom event with custom eventargs, you need to define those or find a way to pass the necessary information through the built in events. Creating events is really easy though so you can look that up online.
I have two forms, one is the main form and the other is an options form. So say for example that the user clicks on my menu on the main form: Tools -> Options, this would cause my options form to be shown.
My question is how can I send data from my options form back to my main form? I know I could use properties, but I have a lot of options and this seems like an tedious odd thing to do.
So what is the best way?
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)
In the comments to the accepted answer, Neeraj Gulia writes:
This leads to tight coupling of the forms Form1 and Form2, I guess instead one should use custom events for such kind of scenarios.
The comment is exactly right. The accepted answer is not bad; for simple programs, and especially for people just learning programming and trying to get basic scenarios to work, it's a very useful example of how a pair of forms can interact.
However, it's true that the coupling that example causes can and should be avoided, and that in the particular example, an event would accomplish the same thing in a general-purpose, decoupled way.
Here's an example, using the accepted answer's code as the baseline:
Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Button1Click += (s1, e1) => Lbl.Text = ((Form2)s1).Message;
frm.Show();
}
}
The above code creates a new instance of Form2, and then before showing it, adds an event handler to that form's Button1Click event.
Note that the expression (s1, e1) => Lbl.Text = ((Form2)s1).Message is converted automatically by the compiler to a method that looks something similar to (but definitely not exactly like) this:
private void frm_Message(object s1, EventArgs e1)
{
Lbl.Text = ((Form2)s1).Message;
}
There are actually lots of ways/syntaxes to implement and subscribe the event handler. For example, using an anonymous method as the above, you don't really need to cast the sender parameter; instead you can just use the frm local variable directly: (s1, e1) => Lbl.Text = frm.Message.
Going the other way, you don't need to use an anonymous method. You could in fact just declare a regular method just like the compiler-generated one I show above, and then subscribe that method to the event: frm.Button1Click += frm_Message; (where you have of course used the name frm_Message for the method, just as in my example above).
Regardless of how you do it, of course you will need for Form2 to actually implement that Button1Click event. That's very simpleā¦
Form2.cs:
public partial class Form2 : Form
{
public event EventHandler Button1Click;
public string Message { get { return txtMessage.Text; } }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
EventHandler handler = Button1Click;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
In addition to the event, I've also declared a property Message that exposes the Text property (and only the Text property, and only as read-only in fact) of the txtMessage control. This allows the subscriber to the event to get the value and do whatever it needs to with it.
Note that all that the event does is to alert the subscriber that the button has in fact been clicked. It's up to the subscriber to decide how to interpret or react to that event (e.g. by retrieving the value of the Message property and assigning it to something).
Alternatively, you could in fact deliver the text along with the event itself, by declaring a new EventArgs sub-class and using that for the event instead:
public class MessageEventArgs : EventArgs
{
public string Message { get; private set; }
public MessageEventArgs(string message)
{
Message = message;
}
}
public partial class Form2 : Form
{
public event EventHandler<MessageEventArgs> Button1Click;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
EventHandler handler = Button1Click;
if (handler != null)
{
handler(this, new MessageEventArgs(txtMessage.Text));
}
}
}
Then the subscriber can just retrieve the message value directly from the event object:
frm.Button1Click += (sender, e) => Lbl.Text = e.Message;
The important thing note in all of the above variations is that at no point does the class Form2 need to know anything about Form1. Having Form1 know about Form2 is unavoidable; after all, that's the object that will create a new Form2 instance and use it. But the relationship can be asymmetrical, with Form2 being usable by any object that needs the features it offers. By exposing the functionality as an event (and optionally with a property), it makes itself useful without limiting its usefulness to only the Form1 class.
The best in this case would be to have some OptionsService class/interface that is accessible via IServiceProvider.
Just add an event when something changes, and the rest of the app can respond to it.
There are lots of ways to perform communication between two Forms.
Some of them have already been explained to you. I am showing you the other way around.
Assuming you have to update some settings from the child form to the parent form. You can make use of these two ways as well :
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");
Properties is one option, shared static class - another option, events - another option...
You might try AutoMapper. Keep your options in a separate class and then use AutoMapper to shuttle the data between the class and the form.
Create a Class and put all your properties inside the class .. Create a Property in the parent class and set it from your child (options) form
You can have a function in Form B like so:
public SettingsResults GetNewSettings()
{
if(this.ShowDialog() == DialogResult.Ok)
{
return new SettingsResult { ... };
}
else
{
return null;
}
}
And you can call it like this:
...
using(var fb = new FormB())
{
var s = fb.GetNewSettings();
...
// Notify other parts of the application that settings have changed.
}
MVC, MVP, MVVM -- slight overkill for someone admittedly saying they want tutorials. Those are theories that have entire courses dedicated to them.
As already posted, passing an object around is probably easiest. If treating a class as an object (interchangeable in this sense) is new, then you may want to spend another 2-4 weeks figuring out properties and constructors and such.
I'm not a C# master by any means, but these concepts need to be pretty concrete if you want to go much further beyond passing values between two forms (also classes/objects in their own right). Not trying to be mean here at all, it just sounds like you're moving from something like VB6 (or any language with globals) to something far more structured.
Eventually, it will click.
This is probably sidestepping your problem a little bit, but my settings dialog uses the Application Settings construct. http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx
I can't find a good example that's similar to how I do it (which is actually having an actual class+object), but this covers another way of doing it:
Reading default application settings in C#
A form is a class, just like any other class. Add some public variables to your form class and set them when they click the button to close the form (technically they are just hiding it).
A VB.NET example, but you'll get the idea -
In your OptionsForm class:
Public Option1 as String = ""
etc. Set them when they hit the "Ok" button.
So in your main form, when they hit the "options" button - you create your options form:
OptionsForm.ShowDialog()
when it exits, you harvest your option settings from the public variables on the form:
option1 = OptionsForm.Option1
etc.
The best way to deal with communication between containers is to implement an observer class
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
(Wikipedia)
the way i do this is creating an Observer class, and inside it write something like this:
1 public delegate void dlFuncToBeImplemented(string signal);
2 public static event dlFuncToBeImplemented OnFuncToBeImplemented;
3 public static void FuncToBeImplemented(string signal)
4 {
5 OnFuncToBeImplemented(signal);
6 }
so basically: the first line says that there would be a function that somebody else will implement
the second line is creating an event that occurs when the delegated function will call
and the third line is the creation of the function that calls the event
so in your UserControl, you should add a function like this:
private void ObserverRegister()//will contain all observer function registration
{
Observer.OnFuncToBeImplemented += Observer_OnFuncToBeImplemented;
/*and more observer function registration............*/
}
void Observer_OnFuncToBeImplemented(string signal)//the function that will occur when FuncToBeImplemented(signal) will call
{
MessageBox.Show("Signal "+signal+" received!", "Atention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
and in your Form you should do something like:
public static int signal = 0;
public void button1_Click(object sender, EventArgs e)
{
Observer.FuncToBeImplemented(signal);//will call the event in the user control
}
and now, you can register this function to a whole bunch of other controls and containers and they will all get the signal
I hope this would help :)
C# windows forms:
Is it possible to create a button that changes the text of a ToolStripMenuItem in another form that is already open?
Something like:
private void button1_Click_1(object sender, EventArgs e)
{
Form1.ToolStripMenuItem.Text = "Some_text";
}
Yes, if the menu created by the form designer the control will be private so you can create a public method or property in the form containing the menu to change the text and call it from the other form.
public void ChangeText(string Text){
this.ToolStripMenuItem.Text = Text;
}
and then call it from outside
Alternately, modify the Form1 designer code so that the private variable for ToolStripMenuItem is public rather than private.
Just had a similar issue, here is my code:
public void UpdateStatusBarUp(string status)
{
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate
{
UpdateStatusBarUp(status);
});
}
else
{
toolStripStatusLabelUp.Text = status;
statusStripUp.Refresh();
}
}
please bear in mind the Refresh() that needed to actually make the change show up in the GUI.
I have two Forms. Say FormA, FormB.
From FormA i called FormB using
frmB.Show();
In FormB, i've two textboxes and a combobox controls.
Assume User enters some data in those two textboxes and selected an item from combobox in Form2 and clicked an OK button.
After the click i want those textboxes user entered values, combobox selected item value back to FormA.
How can i achieve this using C#.
I approached the simple way .. little embellishments..
create public variables in your form class i.e.
public string passVariable1 = "";
if you have text boxes go to properties, then click on the lightning bolt and double click on the empty TextChanged eventhandler. This will create a code snippet in the code begind that gets executed when the content of the textbox changed .. in this code block assign the content of the text box to your corresponding public variable.
i.e. my public variable was
public string issue = "";
private void txtIssue_TextChanged(object sender, EventArgs e)
{
issue = txtIssue.Text;
}
Add a button and create a click event for this button (simply double click on the button in the design pane). In the click event code block set the dilog result to ok and hide the
this.DialogResult = DialogResult.OK;
this.Hide();
In the parent window code check on the dialog result and grab the form data from the child form's public variables
if (f.ShowDialog() == DialogResult.OK)
{
string b = f.issue;
string e = f.year;
string f = f.month;
};
In the scenario that you are describing I would probably call frmB.ShowDialog() rather than frmB.Show().
// Inside FormA open frmB as a modal dialog waiting for
// OK or Cancel result using the following statement
if (frmB.ShowDialog() == DialogResult.OK)
{
// Retrieve selected values from frmB here (while frmB is still not disposed)
}
The benefits of ShowDialog() are that you:
Get the return value from the form easily allowing you to determine that OK (rather than cancel) was clicked to close it.
The form is not immediately disposed when closed thus allowing you to retrieve the values that you want.
By opening frmB as a modal dialog you avoid having to check for the complexities that may occur if your user starts interacting with formA while frmB is open.
NOTE: When designing frmB you have to set the DialogResult property of the OK button-control to DialogResult.OK in order for the form to return the correct DialogResult when this button is pressed (alternatively can also set this.DialogResult in the OK button's Click event handler)
Or you could pass an object from FormA to FormB and bind its properties to the controls in FormB. If you want FormA to be notified when you click OK button you could declare an event in your data container class, subscribe to it in FormA and fire it from FormB.
Be DataContainer some class you define
public class DataContainer
{
public event EventHandler AcceptedChanges;
protected virtual void OnAcceptedChanges()
{
if ((this.AcceptedChanges != null))
{
this.AcceptedChanges(this, EventArgs.Empty);
}
}
public void AcceptChanges()
{
this.OnAcceptedChanges();
}
public string Text1 { get; set; }
public string Text2 { get; set; }
}
in FormA:
private void button4_Click(object sender, EventArgs e)
{
DataContainer data = new DataContainer();
data.Text1 = "text1";
data.Text1 = "text2";
Form2 frm = new Form2();
frm.Data = new DataContainer();
data.AcceptedChanges += new EventHandler(data_AcceptedChanges);
frm.Show();
}
void data_AcceptedChanges(object sender, EventArgs e)
{
// your code here
}
and in FormB:
public DataContainer Data { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add(new Binding("Text", Data, "Text1"));
textBox2.DataBindings.Add(new Binding("Text", Data, "Text2"));
}
private void button1_Click(object sender, EventArgs e)
{
Data.AcceptChanges();
}
You should also implement INotifyPropertyChanging and INotifyPropertyChanged on DataContainer class to play nice with bindings.
You can create an EventHandler on FormB which FormA will subscribe to. Also, add a couple of public properties to FormB that represent that data that you want FormA to be able to use. Then, when FormB fires off the event, FormA will know to refresh his data.
Note: The key principle in this example is implementing an EventHandler (you can create your own event handler type) which notifies FormA when data is ready to be refreshed/viewed/etc. Hopefully, this example will allow you to see how you might implement an event handler for your particular situation.
Example:
FormA -
public partial class FormA : Form
{
//FormA has a private instance of FormB
private FormB formB = null;
public FormA()
{
InitializeComponent();
}
void formB_OnDataAvailable(object sender, EventArgs e)
{
//Event handler for when FormB fires off the event
this.label1.Text = string.Format("Text1: {0}\r\nText2: {1}",
formB.Text1, formB.Text2);
}
private void InitializeFormB()
{
this.formB = new FormB();
//FormA subscribes to FormB's event
formB.OnDataAvailable += new EventHandler(formB_OnDataAvailable);
}
private void button1_Click(object sender, EventArgs e)
{
this.InitializeFormB();
formB.Show();
}
}
FormB -
public partial class FormB : Form
{
//Event that fires when data is available
public event EventHandler OnDataAvailable;
//Properties that expose FormB's data
public string Text1 { get; private set; }
public string Text2 { get; private set; }
public FormB()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Set the exposed properties, then fire off the event.
this.Text1 = this.textBox1.Text;
this.Text2 = this.textBox2.Text;
if (OnDataAvailable != null)
OnDataAvailable(this, EventArgs.Empty);
}
}
A dirty, but also fastest solution is to make those controls public. This you can do by adding the word public in the Form2.Decisgner.cs file. If FormA has a member variable or local variable of FormB, you can access the control (say TextBox1) with:
frmB.TextBox1.Text
which is now accessible outside FormB too.
How about using events and delegates? See this http://colinmackay.scot/2005/04/22/passing-values-between-forms-in-net/
I was having this same issue and came up with an idea which is a bit different. In my scenario, I am making a flashcard program for my youngest two children and I wanted to be able to carry back the answer provided to the parent form (new child form for each new flashcard question so that the parent form can update how many are left, how many correct, how many incorrect, etc.) without having to add values to a database. Seems to be overkill for something that should be simple. What I did was to create a class with 3 of each variable type. I figured three of each type would be sufficient for most jobs.
This is an example of my new class:
namespace ClassNamespace
{
public class ValueHolder
{
public int intValue1 { get; set; }
public int intValue2 { get; set; }
public int intValue3 { get; set; }
public long longValue1 { get; set; }
.
.
.
}
}
I create a new ValueHolder (ValueHolder vh;) from parent form and pass it to the child form. In the child form I create a new ValueHolder and then set it equal to the ValueHolder object sent in the child form's class constructor. Now, when the enter key is pressed (answer given), I can set vh.intValue1 equal to this.answerBox.text;... well, I have to use int.tryparse(); but you get the idea. I then only need to reference vh.intValue1 from the parent form to get the value entered.
Parent form:
for (int i = 0; i < limit; i++)
{
ValueHolder vh = new ValueHolder();
ChildClass cc = new ChildClass(vh);
MessageBox.Show(vh.intValue1.ToString()); //to test that it works
}
and child form:
ValueHolder vh;
public ChildClass (ValueHolder vhIncoming)
{
vh = vhIncoming;
}
private void answerBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
vh.intValue1 = 1234;
}
}
This seems to be the simplest solution for my scenario. I know that this question is old, but wanted to add this option for anyone in a similar position. Just add the class to your project, add more of a type or more types to the class as needed, rinse repeat for future projects.
If its on the same page you should be able to read it directly from your controls as Textbox1.Text, Textbox2.Text, Combobox.SelectedValue (i guess)
But if its on different pages use Session variables like:
Session["date1"] = TextBox1.Text;
Session["date2"] = TextBox2.Text;
Session["comboValue"] = Combobox.SelectedValue;
and use them to populate your form
This would depend on how you normally design your applications.
You could work by using a event
driven system where you would create
events and delegates. Mentioned by #Dave81
Or you could create properties that
return the given/selected values so
that the parent can retrieve them
from the object (Wanted to say Dialog
but not sure about what your using).
Or you can follow #zmilojko and just
set them public, which is basically
the same as creating properties but
more to the dark side of coding
practices :D
All these would work but it all depends on how you like your applications to be structured.
In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.
How can I set the textbox in a form before I show it?
private void button2_Click(object sender, EventArgs e)
{
fixgame changeCards = new fixgame();
changeCards.p1c1val.text = "3";
changeCards.Show();
}
When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.
Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.
So, the code below adds a property to the Form2 class that sets your textbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TextBoxValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
And in the button click event of the first form you can just have code like:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.TextBoxValue = "SomeValue";
form2.Show();
}
You can set "Modifiers" property of TextBox control to "Public"
Try this.. :)
Form1 f1 = (Form1)Application.OpenForms["Form1"];
TextBox tb = (TextBox)f1.Controls["TextBox1"];
tb.Text = "Value";
I know this was long time ago, but seems to be a pretty popular subject with many duplicate questions. Now I had a similar situation where I had a class that was called from other classes with many separate threads and I had to update one specific form from all these other threads. So creating a delegate event handler was the answer.
The solution that worked for me:
I created an event in the class I wanted to do the update on another form. (First of course I instantiated the form (called SubAsstToolTipWindow) in the class.)
Then I used this event (ToolTipShow) to create an event handler on the form I wanted to update the label on. Worked like a charm.
I used this description to devise my own code below in the class that does the update:
public static class SubAsstToolTip
{
private static SubAsstToolTipWindow ttip = new SubAsstToolTipWindow();
public delegate void ToolTipShowEventHandler();
public static event ToolTipShowEventHandler ToolTipShow;
public static void Show()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = true;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
public static void Hide()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = false;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
}
Then the code in my form that was updated:
public partial class SubAsstToolTipWindow : Form
{
public SubAsstToolTipWindow()
{
InitializeComponent();
// Right after initializing create the event handler that
// traps the event in the class
SubAsstToolTip.ToolTipShow += SubAsstToolTip_ToolTipShow;
}
private void SubAsstToolTip_ToolTipShow()
{
if (Vars.MyToolTipIsOn) // This boolean is a static one that I set in the other class.
{
// Call other private method on the form or do whatever
ShowToolTip(Vars.MyToolTipText, Vars.MyToolTipX, Vars.MyToolTipY);
}
else
{
HideToolTip();
}
}
I hope this helps many of you still running into the same situation.
In the designer code-behind file simply change the declaration of the text box from the default:
private System.Windows.Forms.TextBox textBox1;
to:
protected System.Windows.Forms.TextBox textBox1;
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member (for more info, see this link).
I also had the same doubt, So I searched on internet and found a good way to pass variable values in between forms in C#, It is simple that I expected. It is nothing, but to assign a variable in the first Form and you can access that variable from any form. I have created a video tutorial on 'How to pass values to a form'
Go to the below link to see the Video Tutorial.
Passing Textbox Text to another form in Visual C#
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
TextBox txt = (TextBox)frm.Controls.Find("p1c1val", true)[0];
txt.Text = "foo";
}