c# change already open form from another form? - c#

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.

Related

Change picturebox image inside form1 from test.cs

I am trying to update picture box image inside "form1" from another cs file
my code inside test.cs
slot_13.modifier = public;
and inside form1 i wrote this also
CheckForIllegalCrossThreadCalls = false;
test.cs
inventory_Viewer.viewer x = new inventory_Viewer.viewer();
x.slot_13.Image = Image.FromFile(#"C:\Users\Axmed\Google Drive\C# Source Codes\inventory Viewer\inventory Viewer\bin\Release\icon\icon_default.png");
But it doesn't work
If i used this line inside "form1"
x.slot_13.Image = Image.FromFile(#"C:\Users\Axmed\Google Drive\C# Source Codes\inventory Viewer\inventory Viewer\bin\Release\icon\icon_default.png");
image gets changed
Your code misses a lot of context, so I'm going to do a few assumptions. Given a MainForm that shows the InventoryViewerForm and also wants to change the image on the InventoryViewerForm, you could hold a reference to the second form like this:
// Your inventory_Viewer.viewer
public partial class InventoryViewerForm
{
public InventoryViewerForm()
{
}
}
// The form from which to show the viewer.
public partial class MainForm
{
private readonly InventoryViewerForm _inventoryViewerForm;
public MainForm()
{
_inventoryViewerForm = new InventoryViewerForm();
}
private void ShowInventoryViewerButton_Click(object sender, EventArgs e)
{
_inventoryViewerForm.Show();
}
private void ChangeImageButton_Click(object sender, EventArgs e)
{
// Dispose the previously loaded image.
if (_inventoryViewerForm.Image != null)
{
_inventoryViewerForm.Image.Dispose();
}
_inventoryViewerForm.Image = Image.FromFile("NewImage.png");
}
}
But this is bad design altogether. You don't want to tightly couple your forms like this, and you want to leverage the data binding of WinForms and the events of .NET for this. In order to properly implement that, you'll need to show more code.

Control.PerformClick() isn't doing anything, what am I missing?

I've reviewed the MSDN doc and a couple SO answers, and all signs point to this working. At this point, I think I've either completely misunderstood what to expect or I've missed one line of code I need.
In short, I've got a WinForms app with a button, and I want another function to "click" that button at one point in the code. Here's the relevant bits:
// form.Designer.cs
this.btnAddBranch.Click += new System.EventHandler(this.btn_add_Click);
// form.cs
// using statements
public partial class EditClient : Form
{
// ...
public TestClick()
{
//btnAddBranch.PerformClick(); <-- would like to know why this fails ...
btn_add_Click(this, EventArgs.Empty);
}
private void btn_add_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked it!");
}
}
The commented line for btnAddBranch.PerformClick() is what I was hoping would do the equivalent of the line below it. But it doesn't, it doesn't seem to do anything when TestClick() is called. If I do the uncommented line, it works fine.
Am I missing something, or am I totally misunderstanding something?
Your problem is that TestClick() is your form constructor. There are no Controls to call PerformClick() on until the Form Constructor is complete. If you really want to call the code that early then do something like the following.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Do not call methods on controls here, the controls are not yet initialized
}
private void TestClick()
{
btn_add.PerformClick();
}
private void btn_add_Click(object sender, EventArgs e)
{
MessageBox.Show("You Clicked it");
}
private void Form1_Load(object sender, EventArgs e)
{
TestClick();
}
}
Calling your PerformClick() anywhere other than the form constructor will create the desired results.
Sorry, I've updated my answer to correct it. I initially thought it was because you were not calling Button.PerformClick() after Form.InitializeComponent() (from the Form.Designer.cs auto-generated code), but I was corrected that this still does not work.
It seems that the Form is not sufficiently created in the constructor to allow Button.PerformClick(). I theorized that this may due to the fact that the Modal message loop wasn't fully created yet, but after looking at Button.PerformClick's code in Reflector, that doesn't seem to be quite the case.
PerformClick's code looks like this:
public void PerformClick()
{
if (base.CanSelect)
{
bool flag;
bool flag2 = base.ValidateActiveControl(out flag);
if (!base.ValidationCancelled && (flag2 || flag))
{
base.ResetFlagsandPaint();
this.OnClick(EventArgs.Empty);
}
}
}
While looking through, the first failure I notice here is CanSelect will return false because the control is not currently Visible (ShowDialog has not yet been called). Therefore, PerformClick will do nothing as observed. This is by digging down through the CanSelect implementation:
internal virtual bool CanSelectCore()
{
if ((this.controlStyle & ControlStyles.Selectable) != ControlStyles.Selectable)
{
return false;
}
for (Control control = this; control != null; control = control.parent)
{
if (!control.Enabled || !control.Visible)
{
return false;
}
}
return true;
}
In the debugger, you can put a breakpoint in the constructor and see that Button1 will not yet be visible (makes sense).
However, I will suggest that you can accomplish what you want from the constructor, by separating your application logic from the Button's event handler. For example...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoSomething();
}
private void DoSomething()
{
// application logic here...
MessageBox.Show("Hello World");
}
private void button1_Click(object sender, EventArgs e)
{
DoSomething();
}
}
Or, as the previous answer suggests you can call Button.PerformClick() from the Form.OnLoad method. However, it is probably better to just call the application logic directly from both spots instead of performing button clicks in the UI.
Sorry for the initially incorrect answer. Hope this helps explain.
Make sure your form is already Shown :)
If its hidden, or not shown, you cant perform a click.
Atleast this way it worked for me (i show a form for a short moment, perform a click, and hide it immidiately after).
And it works!

passing data from a windows form to a xaml.cs file

I'm using WPF for creating my application, I am calling a windows form using formobject.Show()
from a xaml.cs file,
In the form I have Accept button and a cancel button . How to make the xaml.cs file know which button is clicked by the user in the form.? As the Execution(in ###.xaml.cs) depends on the button clicked.
I solved it, used the property
this.DialogResult = DialogResult.OK; in the the form
and used
if (confirm.DialogResult.ToString() == "OK") in the cs file to check which button is clicked
#Sebastian thanks for the idea.
Do you want to do pure Confirm / Cancel evaluation or do you want to evaluate a more complex result? For cancel / confirm, you can do as described here, using AcceptButton and CancelButton (those are for convenience only, to hook up Esc and Enter with the buttons) and the DialogResult property.
A more complex result is done just the same way, just that you don't set the DialogResult, but a custom property:
public partial class Form1 : Form
{
public string MyProperty { get; set; }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyProperty = "Some complex result";
}
private void button2_Click(object sender, EventArgs e)
{
MyProperty = "Some other complex result";
}
}
You can easily use myWinform.MyProperty to get the value in your XAML.cs file once the modal dialog is closed (the instance is not disposed, since your variable references it).

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