Change picturebox image inside form1 from test.cs - c#

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.

Related

c# winforms array items gets deleted

I know this might look silly but I got a strange problem in my winforms. I have a windows application in which after a particular set of operations are completed I want to populate a Checked ComboBox. I am doing this using two classes. I want to copy a array from helper class to the form class. Array gets copied when AddArrayItems method is called. But when I see the ComboBox in the form, its null. After debugging with watch variables I got to know that the problem is after copying the array to Form1 array, as soon the control goes back to the caller, the array items are deleted. I tried to replicate my stuff, not exactly but still similar to what I am doing.
My code looks like this:
using System;
using System.Windows.Forms;
namespace DemoApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] cboxAr;
public void AddCmboBoxItems(string[] cbArry)
{
cboxAr = new string[cbArry.Length];
Array.Copy(cbArry, 0, cboxAr, 0, cbArry.Length);
//cbArry.CopyTo(cboxAr, 0);
//foreach (string s in cboxAr)
//comboBox1.Items.Add(s);
comboBox1.Show();
}
private void button1_Click(object sender, EventArgs e)
{
HelperClass.DoSomething();
}
}
public class HelperClass
{
public HelperClass()
{
}
public void HelperMethod()
{
SomeMethod();
}
private void SomeMethod()
{
string[] partnrName = new string[5] { "str1", "str2", "str3", "str4", "str5"};
Form1 f = new Form1();
f.AddCmboBoxItems(partnrName);
}
public static void DoSomething()
{
new HelperClass().HelperMethod();
}
}
}
I don't understand what exactly the problem is here. Can anyone please push me in the right direction. Thanks in advance.
You're never showing the form after modifying its controls:
Form1 f = new Form1();
f.AddCmboBoxItems(partnrName);
But you're calling this from within an existing form:
private void button1_Click(object sender, EventArgs e)
{
HelperClass.DoSomething();
}
Presumably you want to modify the controls on that form? Then you'll need a reference to that form. Pass one to the method:
private void button1_Click(object sender, EventArgs e)
{
HelperClass.DoSomething(this);
}
And accept it in the method definition:
public static void DoSomething(Form1 form)
{
new HelperClass().HelperMethod(form);
}
And so until the point where you need to use it. (Side note: You have a lot of weird indirection happening here with a seemingly random mix of static and instance methods and classes. You can simplify a lot, which will make this involve fewer code changes.)
Ultimately, SomeMethod needs the instance of the form to modify:
private void SomeMethod(Form1 form)
{
string[] partnrName = new string[5] { "str1", "str2", "str3", "str4", "str5"};
form.AddCmboBoxItems(partnrName);
}
To illustrate the overall point, consider an analogy...
A car rolls off of an assembly line. You open the trunk and put a suitcase inside. Moments later another car rolls off of the same assembly line. It is identical to the first car in every way. When you open the trunk of the second car, do you expect to find your suitcase inside it?
A Form is an object like any other. Changes made to one instance of an object are not reflected in other instances of the same object. Each instance maintains its own state. In order to modify a particular instance, you need a reference to that instance.

access form's text box value from another class in c# in timer

I want to show DateTime into a text box of a form "Form1".I have created a class "schedule" to create a timer with an interval 1 sec. But cannot access and update Form1's textbox field "xdatetxt". I cannot understand why is it not accessing the controls xdatetxt in Form1.
Schedule.cs
class Schedule{
System.Timers.Timer oTimer = null;
int interval = 1000;
public Form anytext_Form;
public Schedule(Form anytext_form)
{
this.anytext_Form = anytext_form;
}
public void Start()
{
oTimer = new System.Timers.Timer(interval);
oTimer.Enabled = true;
oTimer.AutoReset = true;
oTimer.Start();
oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
}
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{//i want to put here a line like "anytext_Form.xdatetxt.Text = System.DateTime.Now.ToString();"
}
}
in form1.cs:
public partial class Form1 : Form{
public Form1()
{
InitializeComponent();
InitializeScheduler();
}
void InitializeScheduler()
{
Schedule objschedule = new Schedule(this);
objschedule.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
Check this SO thread -
How to access Winform textbox control from another class?
Basically expose a public property that updates Textbox
Make Textbox public
Also note, you need to update Form Controls in UI thread
So you need to get the instance of the form that you want to modify the text. You can do it by passing a reference to the objschedule or by using Application.openforms.
The first way is perfect if you already have the form referenced but if you don, just:
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
dynamic f = System.Windows.Forms.Application.OpenForms["anytext_Form"];
f.xdatetxt.Text=System.DateTime.Now.ToString();
}
There are a few problems here, but both are rather straight-forward to address.
Problem 1: Referencing the form by its base class
Your Schedule class' constructor takes an instance of Form. That is the base class of your Form1 class, and it has no xdatetxt field. Change your Schedule constructor to accept and store an instance of Form1 instead:
public Form1 anytext_Form;
public Schedule(Form1 anytext_form)
{
this.anytext_Form = anytext_form;
}
Problem 2: Updating a control from a non-UI thread
Once you get the compiler error fixed, you will encounter a runtime error. The reason is that the Timer class executes its callback on a background thread. Your callback method attempts to access a UI control from that background thread, and that is not allowed.
I could give a solution inline here, but instead I will point you at another StackOverflow post with far more details about the problem and how to fix it: Cross-thread operation not valid.

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.

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