Call method in Form 1 to set text from user control - c#

I found similar questions to this, but none of the answers solved my question - or perhaps I didn't understand the answers given to implement directly to my scenario.
I have started to learn Windows Forms and my question seems pretty basic.
I have a text box myTextBox in Form1 and created a method in Form1.cs to set the text.
public void SetText(string text)
{
myTextBox.Text = text;
}
I can call this from within Form1.cs and that works fine.
However I have created a user control and within that control I have a button and when I click the button I want to be able to call that SetText method, so I did Form1.SetText("example") but this gave an error for which adding 'static' to the SetText method resolved.
However, when I add static to SetText I can then no longer set the text within that method. I get the same error I had before adding static, only this time for the text box itself:
An object reference is required for the non-static field, method, or property 'Form1.myTextBox'

I don't suggest using SetText because it will be not compitable with other programs else.
Suggested Solutions:
TextBox Property:
Add in your user control TextBox Property and then use it.
Code sample:
In UserControl.cs
public TextBox TargetTextBox { get; set; }
public void SetText(string text)
{
TargetTextBox.Text = text;
}
And use new method that are avaliable in UserControl
Event:
Add event in the user control, and if this event fired in Form1, use SetText in code there.
Sample Code:
Create file called TextEventArgs and put this code:
public class TextEventArgs : EventArgs
{
public TextEventArgs(string text)
{
Text = text;
}
public string Text { get; set; }
}
Use this code in user control
public delegate void ShowTextEventHandler(object sender, TextEventArgs e);
public event ShowTextEventHandler ShowText;
// Use this method, and this method will fire 'ShowText' event
protected override OnShowText(TextEventArgs args)
{
TextEventHandler handler = ShowText;
handler?.Invoke(this, args);
}
Variable (Not suggested):
Go in Program.cs file and put replace it with this code:
using System.Windows.Forms;
public class Program
{
internal static readonly MainForm;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompitableTextRenderer(false);
MainForm = new Form1();
Application.Run(MainForm);
}
}
And then you can use Program.MainForm.SetText("example").

Related

Change text of Button from another form class in C#

I want to modify something in Mission Planner and I want to change button from another class/form in C# in this function :
public void CloseAllConnections()
{
myButton1.Text = "Disconnecting all";
...
}
function that is located in :
namespace MissionPlanner
{
public partial class MainV2 : Form
{
...
}
...
}
the idea is that everything works perfectly when i am focused on that menu, but sometimes i get a error
i even made a function like this
public MyButton GetMyButton1 { get { return myButton1; } }
and also created new instance
var myObject = new MainV2(true);
myObject.myButton1.Text = "Disconnecting all";
nothing works ...
i don't even know where is the function called from, because is clear that is not called from MainV2 class ...
An exception of type 'System.NullReferenceException' occurred in MissionPlanner.exe but was not handled in user code
Any ideas? Thank you.
It appears that your click event form object is called (name) myButton1, and that you are calling the following to change it: myobject.myButton1.Text = "Disconnecting all". Try using myButton1.Text = "Disconnecting all" instead.
You need to grab an instance of the form where the button resides.
Do this by saving a static reference to the form in it's constructor:
namespace MissionPlanner
{
public partial class MainV2 : Form
{
public static MainV2 CurrentForm;
public MainV2()
{
CurrentForm = this;
InitializeComponent();
}
Then somewhere else in your code:
public void CloseAllConnections()
{
MainV2.CurrentForm.myButton1.Text = "Disconnecting all";
...
}
One thing that you could try is to pass the button from the form to the class that will be modifying the button.
public class Example
{
public Button MyButton1 { get; set; }
public Example(Button myButton1)
{
MyButton1 = myButton1;
}
public void CloseAllConnections()
{
MyButton1.Text = "Disconnecting all";
}
}
This should successfully set the button's text on MainV2.
Are you using any sort of multi-threading in your app? if so:
Make sure you either only change the button from the same thread it was created by,
or simply use the ControlInstance.Invoke() method to delegate the change.

c# change already open form from another form?

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.

How to Typecaste a control and access its properties?

IDE: Visual Studio, C# .net 4.0
I have two identical user control uc1 and uc2 and both are having a textbox called txtbox1
now see this code and textbox1 is public in designer so it is assessable in form1.cs, Form 1 is simple windows form which is having uc1 and uc2.
In form1 see this function which i am calling in onLoad_form1 method.
UserControl currentUC; //Global variable;
public void loadUC(string p1)
{
//Here I want:
if(p1 == "UC1)
{
currentUC = uc1;
}
if(p1 == "UC2)
{
currentUC = uc2;
}
}
Than another function which calls update the textbox1 based on currentUC value
//on load
currentUC.textbox1.text = "UC1 called";
//Here I am getting error "currentUc does not contains definition for textbox1"
If i do:
uc1.textbox1.text = "UC1 text";
uc2.textbox1.text = "UC1 text"; //it works, But based on p1 string variable I want to make control as uc1 or uc2 than I want to access its child control. please suggest how to perform this.
please don't tell if else blocks, because This functionality I have to use in various places.
Thanks.
#Lee Answer: - works just for textbox, but I am having two usercontrols i.e. two different usercontrols not instance of it. UserControlLeft and UserControlRight and both are having same textboxes, listboxes etc (with minor design changes), and I want to access/load this based on some string "left" and "right".
Since the textboxes have the same name you can look them up in the Controls collection:
TextBox tb = (TextBox)currentUC.Controls["textbox1"];
tb.Text = "UC1 called";
a better solution would be to add a property to your user control class which sets the internal text property e.g.
public class MyUserControl : UserControl
{
public string Caption
{
get { return this.textbox1.Text; }
set { this.textbox1.Text = value; }
}
}
I think you're mixing a couple of things here.
First of all, you say that you have 2 exactly the same usercontrols, do you mean the ascx files are the same, or that you have 2 instances of the same usercontrol on the page?
Let's go with all the valid options:
1. To find a control and cast it:
Assume you have the following aspx snippet:
<div>
<uc1:MyCustomUserControl id="myControl" runat="server" />
<uc1:MyCustomUserControl id="myControl2" runat="server" />
</div>
If you now want to access the control, you should do the following:
public void Page_Load()
{
var myControl ((MyCustomUserControl)FindControl("MyControlName"));
// On 'myControl' you can now access all the public properties like your textbox.
}
In WPF you can do it like this:
//on load MAINFORM
public void SetText(string text)
{
CLASSOFYOURCONTROL ctrl = currentUC as CLASSOFYOURCONTROL ;
ctrl.SetText(text);
}
// in your control SUB
public void SetText(string text)
{
textbox1.text = "UC1 called"
}
i think this should work in winforms also. And is more clean than accessing the controls from your sub-control directly
#Lee's method is good. Another method will be to use a public property with a public setter (and textbox doesn't need to be public this way).
or an interface (this way you don't care what class you have at the given moment - and no ifs):
public interface IMyInterface
{
void SetTextBoxText(string text);
}
public partial class UC1: UserControl, IMyInterface
{
public void SetTextBoxText((string text)
{
textBox1.Text=text;
}
//...
}
public partial class UC2: UserControl, IMyInterface
{
public void SetTextBoxText((string text)
{
textBox1.Text=text;
}
//...
}
using the code:
((IMyInterface)instanceOfUC1).SetTextBoxText("My text to set");
((IMyInterface)instanceOfUC2).SetTextBoxText("My text to set");

Accessing Form's Control from Custom Control

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";
}
}

How to change text in a textbox on another form in Visual C#?

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";
}

Categories

Resources