Accessing Form3.pictureBox1 out of Form1 - c#

I search a easy way to access different controls on different forms without any workarounds like I would do this e. g. in Visual Basic 6.
Example:
Form3.pictureBox1.Image = MyImage;
But somehow C# doesn't allow accessing another controls on another forms not even from my own classes. I already changed the "pictureBox1" in Form3 to public and still C# doesn't know this control if I type "Form3.".
What I have to do, to access my controls? I already run Visual Studio with elevated privileges (Microsoft answered me on my question in their support area, that elevated privileges are important for accessing the other forms and the controls on it) but nothing helped me sofar. So I stay now with the one form always in C# and this is not suitable to develop any application. Most applications need multiple forms and therefor should be a easy way to access controls from any context in a class or another form. I don't want to use any "set...or get properties" - I do not know even how! Somewhere I found this specific workaround but I usually have so many controls and labels to access in my application, that this would generate a lot of useless overhead, if each control property needs a get- and set-statement or whatever to write to it.
Maybe someone of you knows a more elegant method to do this in a more simple way even if elevation needed.

In VB6 you could access the default instance of your form by using the Class name, in VB.Net they have continued that behavior. C# doesn't have that behavior, therefore you have to create your own instance of your Form. Otherwise you are trying to use it like a static Class. Even though you do not want to, the best way to do want you want is to expose them through properties it keeps everything encapsulated.
Form3 frm3 = new Form3();
frm3.pictureBox1.Image = Image.FromFile("ImageName");
frm3.Show();

I think I know what is wrong. Form1 and Form3 are in fact classes, so typing Form1.something means that something must be a static member. In order to be able to access the picture, you need an instance of the class.
To explain this better, here is an example:
string a;
string is the class type, and a is an instance of that class.
A method to do this would be to modify the startup code (in windows forms that would be in the Program.cs source file), and save the form in a static class, and access it from there.
This is what Program.cs probably looks like:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
You can see that a new instance of Form1 is being created, that is what the new keyword does. You could also do the following:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 f = new Form1();
Application.Run(f);
}
The variable f contains the form being displayed.
I don't really know how your program works, but anyway... to be able to access members of Form3, you need to find the instance. Maybe you have new Form3().Show() somewhere in your code, I don't know exactly... but you need to save that to a variable, and that's how you can access it.

You need to change the modifier property of the objects to public, than you make a instance of the form and call the object you want
Form2 frm2 = new Form2();
frm2.show();
frm2.pictureBox1.Image = "MyImage";

Form3 may refer to the class. You need to use an object to access picturebox1 (or make the field static)

Related

One Common Class to Store Objects of All Forms

I have a windows Forms project with 8 forms. Everytime I open a new Form I do this:
new FormX().Show();
this.Hide();
Due to this, I realized I am creating Multiple objects of Same form while it's previous copies exist, i.e if once i opened FormX and then I hid it and called next Form. When my work was done with it and I had to go back to FormX, I created the object once again. I do not want to do this as this consumes memory and makes application slow.
I want to know if there is a way to store all the objects of all forms in one class/form like this:
Form1 obj1=new Form1();
Form2 obj2=new Form2();
and everytime i need to make one of them visible I simply write obj1.show() or obj2.show()
Is it possible to store these objects in Program.cs class?
The question is somewhat vague. But based on what you seem to be asking, you have a couple of options in addition to the one you propose:
Don't try to reuse the form. Instead of calling Hide() just call Close().
Implement each Form class as a singleton. Then make sure you don't close each form (i.e. continue to call Hide() instead), and access the relevant instance from the static instance property.
Example of #2:
class Form1 : Form
{
private static readonly Lazy<Form1> _instance = new Lazy<Form1>(() => new Form1());
public static Form1 Instance { get { return _instance.Value; } }
}
then elsewhere…
Form1.Instance.Show();
// ... do some stuff with Form1
Form1.Instance.Hide();

Why is there a default instance of every form in VB.Net but not in C#?

I'm just curious to know that there is the (Name) property, which represents the name of the Form class. This property is used within the namespace to uniquely identify the class that the Form is an instance of and, in the case of Visual Basic, is used to access the default instance of the form.
Now where this Default Instance come from, why can't C# have a equivalent method to this.
Also for example to show a form in C# we do something like this:
// Only method
Form1 frm = new Form1();
frm.Show();
But in VB.Net we have both ways to do it:
' First common method
Form1.Show()
' Second method
Dim frm As New Form1()
frm.Show()
My question comes from this first method. What is this Form1, is it an instance of Form1 or the Form1 class itself? Now as I mentioned above the Form name is the Default instance in VB.Net. But we also know that Form1 is a class defined in Designer so how can the names be same for both the Instance and class name?
If Form1 is a class then there is no (Static\Shared) method named Show().
So where does this method come from?
What difference they have in the generated IL?
And finally why can't C# have an equivalent of this?
This was added back to the language in the version of VB.NET that came with VS2005. By popular demand, VB6 programmers had a hard time with seeing the difference between a type and a reference to an object of that type. Form1 vs frm in your snippet. There's history for that, VB didn't get classes until VB4 while forms go all the way back to VB1. This is otherwise quite crippling to the programmer's mind, understanding that difference is very important to get a shot at writing effective object oriented code. A big part of the reason that C# doesn't have this.
You can get this back in C# as well, albeit that it won't be quite so clean because C# doesn't allow adding properties and methods to the global namespace like VB.NET does. You can add a bit of glue to your form code, like this:
public partial class Form2 : Form {
[ThreadStatic] private static Form2 instance;
public Form2() {
InitializeComponent();
instance = this;
}
public static Form2 Instance {
get {
if (instance == null) {
instance = new Form2();
instance.FormClosed += delegate { instance = null; };
}
return instance;
}
}
}
You can now use Form2.Instance in your code, just like you could use Form2 in VB.NET. The code in the if statement of the property getter should be moved into its own private method to make it efficient, I left it this way for clarity.
Incidentally, the [ThreadStatic] attribute in that snippet is what has made many VB.NET programmers give up threading in utter despair. A problem when the abstraction is leaky. You are really better off not doing this at all.
VB is adding a load of code into your project behind your back, basically.
The easiest way to see what's going on is to build a minimal project and look at it with Reflector. I've just created a new WinForms app with VB and added this class:
Public Class OtherClass
Public Sub Foo()
Form1.Show()
End Sub
End Class
The compiled code for Foo looks like this when decompiled as C#:
public void Foo()
{
MyProject.Forms.Form1.Show();
}
MyProject.Forms is a property in the generated MyProject class, of type MyForms. When you start diving into this you see quite large amounts of generated code in there.
C# could do all of this, of course - but it doesn't typically have a history of doing quite as much behind your back. It builds extra methods and types for things like anonymous types, iterator blocks, lambda expressions etc - but not in quite the same way that VB does here. All the code that C# builds corresponds to source code that you've written - just cleverly transformed.
There are arguments for both approaches, of course. Personally I prefer the C# approach, but that's probably no surprise. I don't see why there should be a way of accessing an instance of a form as if it was a singleton but only for forms... I like the language to work the same way whether I'm using GUI classes or anything else, basically.

How do I use a custom constructor in a WinForm?

I need to instantiate a Winform within another project. How is this done? I am currently attempting to chain the default constructor. It seems that my custom constructor is not called.
Also.. the entry point for this application will not be in the project that owns this form. Meaning the following will not run:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new HtmlTestForm());
I am not entirely sure what this code is doing. Will the form still function?
private HtmlTestForm()
{
InitializeComponent();
OpenBrowser(new Uri(TestURL));
}
public HtmlTestForm(Uri uri)
:this()
{
TestURL = uri;
}
//New up form in another project.
HtmlTestForm form = new HtmlTestForm(new Uri("http://SomeUri.html"));
The form will work.
However, TestURL will only be assigned after the OpenBrowser call. (: this() will execute the entire default constructor first)
Instead, you should probably call InitializeComponent separately in your custom constructor and not chain to the default.
.Net form classes are normal classes that happen to contain an automatically generated method called InitializeComponent.
They do not have any magic that you need to be aware of (unlike VB6); as long as you understand the purpose of InitializeComponent (read its source), you can do anything you want with them.

How to access form objects from another cs file in C#

In the form.cs file I have two buttons,a memo and a timer.My question is: How do I access the timer or the memo from another cs file?
I've tried to make the objects public,but it didn't work,please give me a source or a project,so I can see where I'm mistaken.
Thanks!
Select your button in designer, go to it's properties and change "Modifiers" property from Private to Public.
Then you can get access to it from another class, something like this:
public static class Test
{
public static void DisalbeMyButton()
{
var form = Form.ActiveForm as Form1;
if (form != null)
{
form.MyButton.Enabled = false;
}
}
}
Note: it's just an example and definitely not a pattern for good design :-)
I worry whenever I hear someone talking about "another .cs file" or "another .vb file". It often (though not always) indicates a lack of understanding of programming, at least of OO programming. What's in the files? One class? Two?
You're not trying to access these things from another file, you're trying to access them from a method of a class, or possibly of a module in VB.
The answer to your question will depend on the nature of the class and method from which you're trying to access these things, and the reason why you want to access them.
Once you edit your question to include this information, the answers you receive will probably show you that you shouldn't be accessing these private pieces of the form in classes other than the form class itself.
There is Form object already instanced in Program.cs, except it have no reference. With simple editing you can turn
Application.Run(new Form1());
to
Application.Run(formInstance = new Form1());
declare it like
public static Form1 formInstance;
and use
Program.formInstance.MyFunction(params);
Although I agree with John Saunders, one thing you may be doing wrong, assuming that you have everything accessible through public modifiers, is that you don't have the instance of that form.
For example, this is how you would do it:
Form1 myForm = new Form1;
string theButtonTextIAmLookingFor = myForm.MyButton.Text;
I am assuming that you may be trying to access it like it's static, like this:
string theButtonTextIAmLookingFor = Form1.MyButton.Text;
Just something you might want to check.
The intuitive option is simply to make the control field public
Here is a very good solution to solve this issue..
http://searchwindevelopment.techtarget.com/answer/In-C-how-can-I-change-the-properties-of-controls-on-another-form

Best way to access a control on another form in Windows Forms?

First off, this is a question about a desktop application using Windows Forms, not an ASP.NET question.
I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...
otherForm.Controls["nameOfControl"].Visible = false;
It doesn't work the way I would expect. I end up with an exception thrown from Main. However, if I make the controls public instead of private, I can then access them directly, as so...
otherForm.nameOfControl.Visible = false;
But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form?
Further Explanation:
This is actually a sort of follow-up to another question I asked, Best method for creating a “tree-view preferences dialog” type of interface in C#?. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.
Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)
Instead of making the control public, you can create a property that controls its visibility:
public bool ControlIsVisible
{
get { return control.Visible; }
set { control.Visible = value; }
}
This creates a proper accessor to that control that won't expose the control's whole set of properties.
I personally would recommend NOT doing it... If it's responding to some sort of action and it needs to change its appearance, I would prefer raising an event and letting it sort itself out...
This kind of coupling between forms always makes me nervous. I always try to keep the UI as light and independent as possible..
I hope this helps. Perhaps you could expand on the scenario if not?
The first is not working of course. The controls on a form are private, visible only for that form by design.
To make it all public is also not the best way.
If I would like to expose something to the outer world (which also can mean an another form), I make a public property for it.
public Boolean nameOfControlVisible
{
get { return this.nameOfControl.Visible; }
set { this.nameOfControl.Visible = value; }
}
You can use this public property to hide or show the control or to ask the control current visibility property:
otherForm.nameOfControlVisible = true;
You can also expose full controls, but I think it is too much, you should make visible only the properties you really want to use from outside the current form.
public ControlType nameOfControlP
{
get { return this.nameOfControl; }
set { this.nameOfControl = value; }
}
After reading the additional details, I agree with robcthegeek: raise an event. Create a custom EventArgs and pass the neccessary parameters through it.
Suppose you have two forms, and you want to hide the property of one form via another:
form1 ob = new form1();
ob.Show(this);
this.Enabled= false;
and when you want to get focus back of form1 via form2 button then:
Form1 ob = new Form1();
ob.Visible = true;
this.Close();
I would handle this in the parent form. You can notify the other form that it needs to modify itself through an event.
Use an event handler to notify other the form to handle it.
Create a public property on the child form and access it from parent form (with a valid cast).
Create another constructor on the child form for setting form's initialization parameters
Create custom events and/or use (static) classes.
The best practice would be #4 if you are using non-modal forms.
You can
Create a public method with needed parameter on child form and call it from parent form (with valid cast)
Create a public property on child form and access it from parent form (with valid cast)
Create another constructor on child form for setting form's initialization parameters
Create custom events and/or use (static) classes
Best practice would be #4 if you are using non-modal forms.
With the property (highlighted) I can get the instance of the MainForm class. But this is a good practice? What do you recommend?
For this I use the property MainFormInstance that runs on the OnLoad method.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LightInfocon.Data.LightBaseProvider;
using System.Configuration;
namespace SINJRectifier
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
UserInterface userInterfaceObj = new UserInterface();
this.chklbBasesList.Items.AddRange(userInterfaceObj.ExtentsList(this.chklbBasesList));
MainFormInstance.MainFormInstanceSet = this; //Here I get the instance
}
private void btnBegin_Click(object sender, EventArgs e)
{
Maestro.ConductSymphony();
ErrorHandling.SetExcecutionIsAllow();
}
}
static class MainFormInstance //Here I get the instance
{
private static MainForm mainFormInstance;
public static MainForm MainFormInstanceSet { set { mainFormInstance = value; } }
public static MainForm MainFormInstanceGet { get { return mainFormInstance; } }
}
}
I agree with using events for this. Since I suspect that you're building an MDI-application (since you create many child forms) and creates windows dynamically and might not know when to unsubscribe from events, I would recommend that you take a look at Weak Event Patterns. Alas, this is only available for framework 3.0 and 3.5 but something similar can be implemented fairly easy with weak references.
However, if you want to find a control in a form based on the form's reference, it's not enough to simply look at the form's control collection. Since every control have it's own control collection, you will have to recurse through them all to find a specific control. You can do this with these two methods (which can be improved).
public static Control FindControl(Form form, string name)
{
foreach (Control control in form.Controls)
{
Control result = FindControl(form, control, name);
if (result != null)
return result;
}
return null;
}
private static Control FindControl(Form form, Control control, string name)
{
if (control.Name == name) {
return control;
}
foreach (Control subControl in control.Controls)
{
Control result = FindControl(form, subControl, name);
if (result != null)
return result;
}
return null;
}
#Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right?
You have my sympathy! ;)
#Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates many child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :)
Do your child forms really need to be Forms? Could they be user controls instead? This way, they could easily raise events for the main form to handle and you could better encapsulate their logic into a single class (at least, logically, they are after all classes already).
#Lars: You are right here. This was something I did in my very beginning days and have not had to do it since, that is why I first suggested raising an event, but my other method would really break any semblance of encapsulation.
#Rob: Yup, sounds about right :). 0/2 on this one...
You should only ever access one view's contents from another if you're creating more complex controls/modules/components. Otherwise, you should do this through the standard Model-View-Controller architecture: You should connect the enabled state of the controls you care about to some model-level predicate that supplies the right information.
For example, if I wanted to enable a Save button only when all required information was entered, I'd have a predicate method that tells when the model objects representing that form are in a state that can be saved. Then in the context where I'm choosing whether to enable the button, I'd just use the result of that method.
This results in a much cleaner separation of business logic from presentation logic, allowing both of them to evolve more independently — letting you create one front-end with multiple back-ends, or multiple front-ends with a single back-end with ease.
It will also be much, much easier to write unit and acceptance tests for, because you can follow a "Trust But Verify" pattern in doing so:
You can write one set of tests that set up your model objects in various ways and check that the "is savable" predicate returns an appropriate result.
You can write a separate set of that check whether your Save button is connected in an appropriate fashion to the "is savable" predicate (whatever that is for your framework, in Cocoa on Mac OS X this would often be through a binding).
As long as both sets of tests are passing, you can be confident that your user interface will work the way you want it to.
This looks like a prime candidate for separating the presentation from the data model. In this case, your preferences should be stored in a separate class that fires event updates whenever a particular property changes (look into INotifyPropertyChanged if your properties are a discrete set, or into a single event if they are more free-form text-based keys).
In your tree view, you'll make the changes to your preferences model, it will then fire an event. In your other forms, you'll subscribe to the changes that you're interested in. In the event handler you use to subscribe to the property changes, you use this.InvokeRequired to see if you are on the right thread to make the UI call, if not, then use this.BeginInvoke to call the desired method to update the form.
Step 1:
string regno, exm, brd, cleg, strm, mrks, inyear;
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string url;
regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text;
cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text;
strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text;
mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text;
inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text;
url = "academicinfo.aspx?regno=" + regno + ", " + exm + ", " + brd + ", " +
cleg + ", " + strm + ", " + mrks + ", " + inyear;
Response.Redirect(url);
}
Step 2:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string prm_string = Convert.ToString(Request.QueryString["regno"]);
if (prm_string != null)
{
string[] words = prm_string.Split(',');
txt_regno.Text = words[0];
txt_board.Text = words[2];
txt_college.Text = words[3];
}
}
}
public void Enable_Usercontrol1()
{
UserControl1 usercontrol1 = new UserControl1();
usercontrol1.Enabled = true;
}
/*
Put this Anywhere in your Form and Call it by Enable_Usercontrol1();
Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal
*/
Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties.
Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier.
But some strange!
I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else.
I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently.
But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)),
Or
Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new Form() construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more.
You declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well.
Consider This Example.
Suppose you want to access to a Form's TextBox.
So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future).
Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing.
Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class.
Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open.
Look at code below (We have three object.
1- a static class (in our example we name it A)
2 - Any Form else which wants to open the final Form (has TextBox, in our example FormB).
3 - The real Form which we need to be opened, and we suppose to access to its internal TextBox1 (in our example FormC).
Look at codes below:
internal static class A
{
internal static FormC FrmC;
}
FormB ...
{
'(...)
A.FrmC = new FormC();
'(...)
}
FormC (Designer File) . . .
{
internal System.Windows.Forms.TextBox TextBox1;
}
You can access to that static Variable (here FormC) and its internal control (here Textbox1) wherever and whenever as you wish, while FormC is open.
Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion.

Categories