C#: set active form, change field on that form - c#

I'm trying to add an item to listBox1 that's on Form4 from Form5. I researched it and found an answer on this site that is supposed to work:
var form = Form.ActiveForm as Form4;
form.listBox1.Items.Add("aaa");
I get a "NullReferenceException". That's the solution I found but I don't even understand why it should work. My instance of Form4 is called formfour and I create like this from the main form:
Form4 formfour = new Form4();
formfour.Show();
The listBox1 modifiers is set to public.

The reason you are getting the NullRefereneException is that your current ActiceForm is not being casted as Form4, that is why you get null in your instance form.
From the question it appears that you have Form4 opened and you want to set that form as active:
You can use Application.OpenForms property and get an instance of Form4 like:
Form4 form = Application.OpenForms["Form4"] as Form4;
if(form != null)
form.Focus();
also if you want to add items to list box on existing form then:
form.listBox1.Items.Add("aaa");

In Form5
Form4 frm4= new Form4();
frm4.listbox.Items.Add("aaa");
// make sure that the listbox on form4 is set to public from its properties
To refresh the form4 use
frm4.refresh();
And for more go through this link

Related

Form 2 With ListBox Value Pass In Form4 Label "Help Me"

this listbox value pass in Form 4 If I Will Select
i Will Try This Command
Form4 f4 = new Form4();
F4.label.Text = lisbox1.Selectitem.Tostring();
I Will Select Control SelectIndexChanger
this Is label Form4 select listbox value Show here
You can pass parameters through the constructor
Form 4
public partial class Form4 : Form
{
public Form4(string value)
{
F4.label.Text = value;
}
}
In Form 1
Form4 form = new Form4(lisbox1.Selectitem.Tostring());
form.ShowDialog();
Hope to help you

Create a new form instance inside parent with the ability to access the parent form

I tried to create a new form inside the Parent. I set FormBorderStyle to none.
When I am adjusting MDIParent to the myForm, it gave me a sick looking error like this:
System.ArgumentException : The given Form is not being recalled as a MdiContainer.
This is my code for creating a new Windows Form.
FrmHome myForm = new FrmHome ();
myForm.TopLevel = false;
pnlContainer.Controls.Add(myForm);
myForm.Show();
The Mdi parent must have it's IsMdiContainer property set to True.
You can set this property at design time in your main form or runtime :-
Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();
Form1 is the name of the form that you want to show.
Form.IsMdiContainer Property
Property Value
Boolean
true if the form is a container for MDI child forms; otherwise, false.
The default is false.

Is there any other way to access open forms in C#?

Application.OpenForms["formname"];
Is there any other way to access an open form. My application doesn't see this form although it is opened. I dont know why.
Isn't really necessary a name to get an open form.
You can get the form you want by index:
Form frm = Application.OpenForms[0] //Will get the main form
Form frm = Application.OpenForms[1] //Will get the first child
Forms in the OpenForms collection are ordered in the same way that you create it
Otherwise, an alternative is to save a reference to the form and then accessing it by this reference.
//Where you want to save the reference:
Form theForm;
//Where you create the form:
myClass.theForm = new MyForm();
//Where you want to get that form:
MessageBox.Show(myClass.theForm.Caption);
(myClass is the class that will hold your reference to the form, supposing you are accessing it from different classes)
(Also, see if you are affected by this: Application.OpenForms.Count = 0 always)
I recommend you to firstly debug your code to check what is the Form actual name which you want to load:
foreach (Form form in Application.OpenForms) {
string name = form.Name; //check out this name!!
//print, or anything else will do, you only want to get the name
//note that you should be able to get any form as long as you get its name correct
}
And then, once you know what is wrong with your code, simply do:
Form form = Application.OpenForms[name]; //use the same name as whatever is available according to your debug
To get your form.
To check more on the possible bugs, See Hans Passant's Post
You have to instanciate first a Form. after that you have access to it:
Form1 formname = new Form1();
Application.Run(formname);
// access to form by formname.yourproperty
To access the form using this property your form must have a Name.
Remember its not the instance name nor the the form Text:
Form1 f1 = new Form1(); //not "f1" is the "Name"
f1.Text = "it is title of the form"; //neither "Text" is the "Name"
f1.Name= "its the name"; //it is the "Name"
Sample:
frm_myform form1 = new frm_myform();
frm_myform.Name = "form1";

Creating Edit dialog box in Windows Forms C#

I have Form1.cs which has two buttons say "ADD" and "EDIT".
Clicking "ADD" shows dialog Form2.cs.
Form2 has a TextBox and a ComboBox. Say we enter value "A" in textbox and select "A" from ComboBox.
Then close Form2.
Then when EDIT button is clicked on Form1, Form2 should show up with "A" in textbox and "A" selected in ComboBox.
This is a simple explanation. The real form I am using has around 10-12 different controls including combobox, checkbox, textbox etc.
My main doubt is where and how do we save these control values.
Is there a specific approach to this type of DialogBoxes that I am missing?
Create class, that would store values that you want to pass (let's call it Foo).
Form2 should then have a property. In the setter of the property, set controls:
public partial class Form2 : Form
{
private Foo _bar;
public Foo Bar
{
set
{
_bar = value;
//set your controls here
}
}
On Edit button, set property like this:
Form2 form2 = new Form2();
form2.Bar = bar; //bar contains values to edit
Then put a Save button on Form2, that would save values back from controls to this object.
For every control I would have a field in Foo class, eg. string for textboxes, bool for checkboxes and enum or int for comboboxes (where integer value would equal selected index).
Alternatively, you could use Dictionary class instead and have key and value pair for every control.
You can also have some enum, if your form looks or behaves differently in New and Edit mode.
Your Dialog Form should have a field containing the properties/fields you want, a copy a business object for example. Then you pass it or initialize it in your dialog constructor or Load, depending the behavior you want. From there you can create / initialize your controls.
If you want a built in system you may wanna take a look to the PropertyGrid (which you could embedded in a dialog (to fit your question))
Do you want to just load the last value user entered there?
For instance he writes "text" on the textbox and chooses "A" combobox it should be pre-selected next time you open it?
Edit: Then instead of closing it using Form.Close make it so that it hides. Form1.Hide. Next time it opens values are still saved. Unless application has been closed. In the other hand, users might click on the close button in the windows form. You can either make it "unclickable" throught proprieties or just configure it using events i think.
Create a method on Form2, where you will set values into textBox and select an item in comboBox. Call this method just after instantiating form2 and before showing it.
Example:
public Form2()
{
InitializeComponent();
comboBox1.Items.AddRange(new string[] { "a", "b", "c" });//fill comboBox your way on a loading time
}
public void UpdatingControls(string a, string b)
{
textBox1.Text = a;
comboBox1.SelectedText = b;
}
//on form2;
Form1 f2;
private void OpenForm2Button_Click(object sender, EventArgs e)
{
f2 = new Form2();
f2.UpdatingControls("a", "b"); //a will go into textBox, b will be choosen in comboBox
}
public Form2(string form1Textbox)
{
InitializeComponent();
form2Textbox.Text = form1Textbox;
}

Accessing controls on a new form

I have 2 forms in my project, form1 and form2. When I click in a button in form1 I run this code:
Form tempform = new Form2();
tempform.Show();
In my code for Form2 I have a label which I now need to change the text.
How can I access the label?
I tried:
tempform.label1.value = "new text"
And that didn't work, I even tried to access using the Controls collection but I think I messed that up. Is there any way I can access the label? OR is there any way I can pass a value to that new form and then have that form alter the label text.
Thanks
If the label value should only be set once, when the form is created, then use a constructor for Form2 like this:
public Form2(string labelValue)
{
_labelValue = labelValue;
}
and then call that constructor when you create the form.
Alternatively, if the label changes over the lifetime of the form, make a public property:
public string LabelValue
{
get { return label1.Text; }
set { label1.Text = value; }
}
Also I would recommend naming the parameters and/or properties to reflect the meaning of the value, for example "titleText" instead of "labelValue". That way Form2 can decide how it wants to display the information (in the title bar, a label, a textbox, etc), and Form1 doesn't have to worry about that.
Edit: Consume the LabelValue property like this:
Form2 newForm = new Form2(); // Assign object to a Form2 instead of Form
newForm.LabelValue = "new text";
newForm.Show();
Controls have protected access by default. You can change that to public, or you can add a method/property to your form2 class to set the label and call that (latter method is generally preferred to preserve encapsulation and because the designer may want to overwrite your public change.).

Categories

Resources