In my program I have two forms. The main form and a form where you fill in extra information. What I'm trying to do is to write out the information given on the second form on a list box when the 'ok' button is pressed.
Currently this is what I have:
Main form:
public void writeLine()
{
foreach (var item in VarClass.listItems[VarClass.count - 1])
{
listBox1.Items.Add(item.ToString());
}
}
Second form:
Form1.writeLine();
As it, I get the following error at 'Form1.writeLine();'
"An object reference is required for the non-static field, method or property..."
I can kinda fix this by making 'writeLine()' static in the main form, but then I get the same error on 'listBox1' in the main form. How do I fix this?
You should pass the reference of your main form to the second form and call the method on that reference. For example you can create a property on the second form like private Form _mainForm; and create a constructor of the second form to receive that reference and set to that field. After that you will be able to call _mainForm.writeLine() in your second form.
Create an instance of Form1 and call the method. Here is the code:
new Form1().writeLine();
There are a couple ways to handle this. One is for form2 to have a reference back to the calling form ideally through an interface rather than a reference to the concrete class.
Another option would be for Form2 to have an event that form1 could subscribe to that would inform form1 that form2 has some output.
Keep a reference to the second form from the first:
public MyFirstForm
{
...
public MyFunction()
{
MySecondForm secondForm = new MySecondForm();
// ... Open your form etc, look for when it's complete and then ...
// Read the values from the second form into the first
var MyValues = secondForm.getValues();
// Now populate the list-box with the information returned.
//for (my listbox)
}
}
Related
It's probably a silly question, but I really don't know how to handle it.
My main form default class looks like this:
public partial class MainForm : Form
{
public MainForm(bool version)
{
InitializeComponent();
if(version == true)
{
items_checkedListBox.Items.Add("aa".ToString());
}
else
{
Controls.Remove(items_checkedListBox);
}
}
}
By default, my WinForm app starts with Application.Run(new MainForm(true)); and everything is ok. But I want to update the checkedListBox from another class and for that I need to instantiate my main form object and I call the new object with MainForm mainForm = new MainForm(false); but the problem is that the checkedList control remains, even though Controls.Remove(items_checkedListBox); gets executed.
How could I manipulate a control from another class when I instantiate the main form? :(
By doing this:
MainForm mainForm = new MainForm(false);
you create a new second form of the type MainForm and delete it's control items_checkedListBox, but that's not the control which you see on your first form of MainForm. Furthermore you don't see the second form you created, because you didn't make it show up, so don't wonder that you don't see anything happening like the removal of the other control on the second form.
So in order to manipulate your control items_checkedListBox you need to pass the reference of this control to your class in which you wish to manipulate it.
Imagine you would have another form (which is your other class), which you use to manipulate your control items_checkedListBox.
public partial class FmManipulateControl : Form
{
public FmManipulateControl()
{
InitializeComponent();
}
}
In order to be able to do this, pass a reference of this control as method parameter to the constructor:
public FmManipulateControl(Control myControl) { ... }
So that we can manipulate it we store this reference of our control in a field, so e.g. a button click event can access the control to change/remove/... it.
Control controlToChange;
public FmManipulateControl(Control myControl)
{
InitializeComponent();
controlToChange = myControl;
}
Let's imagine we bind to a button click event in our form FmManipulateControl:
private void button1_Click(object sender, EventArgs e)
{
//diposes the control, so it does not exist anymore, but you can apply
//any change to the control you wish to do
controlToChange.Dispose();
}
Now all you have to do is to create an instance of FmManipulateControl and pass it a reference of the control items_checkedListBox and show the new form object.
FmManipulateControl fmChangeAControl = new FmManipulateControl( items_checkedListBox);
fmChangeAControl.Show();
Further explaination about the reference type:
I am talking about passing a reference of the control and I think you might wonder about what I mean by that. I suggest you to read about value and reference types.
I try to keep it short and simple.
Imagine a value type contains the value directly itself: e.g. an int. The object contains the value directly.
int a = 3;
a contains the value 3.
Now let's have a look at our control. This ListBox control items_checkedListBox does not contain our object control, but a reference to it's location in memory. That's why it is called reference type.
So when we pass items_checkedListBox as a method parameter, we don't pass an object, but the memory location of our items_checkedListBox control. So we point to the same object, so we are abel to manipulate it.
Note:
Method parameters are just a copy of the inputted object, so when we do:
FmManipulateControl fmChangeAControl = new FmManipulateControl( items_checkedListBox);
In our form fmChangeAControl we got an object(myControl) which is a copy of items_checkedListBox. But since we did not pass the object, but a reference it does not matter if we have a copy or not, we still point to the same memory location so we still manipulate the same object.
I have made a windows form application (which has been running fine for more than couple of weeks). Now I wanted to add another form in it (which should be displayed to show extra properties of item whose value is being shown in rich textbox)
Here is my code for double click (to show details window):
private void richTextBox1_DoubleClick(object sender, EventArgs e)
{
//Using parameterized constructor since I need an input from parent form
Form2 formETView = new Form2(richTextBox1.Text.Substring(1, 15));
formETView.Show();
}
As a reference, constructor of Form2 is:
public Form2(string p)
{
// TODO: Complete member initialization
trans_ID = p;
}
But it shows only this screen:
While actual screen has couple of controls:
Any help in this regard will be really appreciated.
P.S: Is the approach to use parameterized constructor to pass data as argument in child window incorrect? Please let me know if it's the case.
Use
public Form2(string p) : this()
This way you call default constructor that calls InitializeComponents.
Just call InitializeComponent() in your constructor function. That initializes all the controls of the form.
I am sure this is an easy question to answer, but I am having difficulty implementing it how I need.
I am using Visual Studio 2013 and C#
I have two forms, one that loads when the app starts up which contains user-selectable settings such as user id, how many puzzle pieces that would like on screen... and a confirm button.
The second form is like a puzzle grid, which is generated when the user clicks the confirm button on the first form.
When the person has correctly solved the puzzle, a message box pops up with the time it took to solve.
What I want to be able to do is add the user id field into the messagebox string.
I have seen many examples of using event args and getting and setting fields but most are assuming one form is generated from a previous form, where I just want to 'grab' the information from one form and store it on the second form for use in a string.
Links to tutorials would also be appreciated if that is easier.
I found out what I was doing wrong, with the help of everyone's answers.
I had the variables declared on the first form, but they were declared in the textbox_leave and updownBox_leave methods when they should have been declared at the very top of the class.
Then I just called Form1.IdString and Form1.puzzleNumberString from my Form2 and what-do-you-know everything went as I thought it should.
It's pretty simple.All you need to do is pass your id variable to second form constructor.For example in your Confirm Button click:
Form2 f2 = new Form2(myVariable);
f2.Show();
And you should add a constructor to the Form2:
public string ID { get; set; }
public Form2(string id)
{
InitializeComponent();
ID = id;
}
Then you can use ID variable in your second form.
In your puzzle form create a global Form variable, then give the constructor a Form f parameter and set your global form variable as the passed parameter:
public Form form = null;
public PuzzleForm(Form f) //puzzle form constructor
{
form = f;
}
then go into your first form and where you create an instance of the puzzle form change it so that it passes an instance of this.
PuzzleForm pf = new PuzzleForm(this);
Now from inside your Puzzle form you can access your Form1 variables like so MessageBox.Show("UserID: "+form.userID.Text);
i'm trying to make a second form and acces to all of the main form methods, values, etc... so what i do is:
public partial class Principal : Form
{
public Principal()
{
InitializeComponent();
}
...
And in one method i have...
private void agregarUsuarioToolStripMenuItem_Click(object sender, EventArgs e)
{
Form Form2 = new Form();
Form2.Show();
}
I suppose that in Form2 i could acces to all of what i have in my main form, but i wonder how to edit this Form2, how to put buttons or stuff, cause i didnt create a form, just another instance of Form().
First of all, you cannot access the values on the main form from the second form unless the second form has a reference to the first main form. They are completely separate instances. The second form is only another copy of the template (the type) that the first form was created from. All state or data in the first form is specific to the instance of the form (unless declared as static). All the controls and visual elements defined in the forms template are created in each of the instances from the template when the form is instantiated (when the constructor runs).
If you need the second form to refer to values on the first form, how to do this best depends on how, when and why.... If you only need to do this when the second form is constructed, and never again during the lifetime of the first form, then you can do it during construction ( Form Form2 = new Form(); ) if you have a reference to the first instance of the form. If you need access to the values on the first instance later as well (during the lifetime of the second instance), then you need to add a reference to the first instance as a private field or property of the form so that code on instances of the second form will always have a reference to the first instance. The best way os to make the second instance an instance of a derived (child) of the first form that has this additional property, and pass the reference to the first form in the constructor to of this second derived form type
public SecondForm: Principal
{
public Form PrincipalForm { get; set; }
public SecondForm(Principal principalForm)
{
InitializeComponent();
PrincipalForm = principalForm;
}
// other stuff
}
then, when you create the second instance, create an instance of SecondForm instead. It will look exactly like the first instance, (cause it derives everything defined on Principal), but will have this one additional property.
private void agregarUsuarioToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondForm Form2 = new SecondForm(firstPrincipalForm);
Form2.Show();
}
now, everywhere on the second forms internal and public methods and code you will have a reference to the first form to do with as you wish
I have an application that shows data from a MySQL table. Basically, my application consists of two forms: the main form, and a form for adding stuff to the database.
The main form shows all the entries in the database and relevant information. When the user wants to add a new entry to the database, a secondary form is opened that prompts for information. Once the information is filled out, the user presses a Submit button and the form closes. My problem is that when the secondary form closes, the listBox in the main form doesn’t update to reflect the newly-added entry.
Here is the code that is executed when the user submits the secondary form:
private void closeWindow()
{
mainForm parent = new mainForm();
parent.listParts.Refresh();
this.Close();
}
Is there a reason when I call the listBox to be refreshed, it doesn’t show my newly-added information? Perhaps I am calling something in the wrong order? Or does the Refresh() method not even work like that?
Any help would be appreciated! Alternatively, if you know of a better way to do this, I’d love to hear it!
The problem is that you're refreshing the wrong form:
private void closeWindow()
{
mainForm parent = new mainForm();
parent.listParts.Refresh();
this.Close();
}
Since you use: new mainForm(), you're allocating a completely separate instance of the "mainForm", and refreshing it's content. This will not effect the existing, opened form.
I would recommend passing a reference to the mainForm to the constructor of the secondary form. It then would know which instance of mainForm it needs to use to call Refresh().
Reed has given an answer with why what you did din't work, here's one possible solution for how to actually fix it:
in some event handler for MainForm:
var otherForm = new SomeOtherForm();
otherForm.Closed += (sender, args) =>
{
//update the listbox in MainForm here
};
If you need information from the second form to update the listbox, then make a public property in SomeOtherForm that exposes the data needed by MainForm.
I think you should reload the data again. fetch it again set the datasource
Have a Parent Property to your child form which is of type of your First form.
some thing like this.
Your Parent form
public partial class KitTypes : Form
{
public void ReloadData()
{
// Get the data and Set as datasource of control
}
}
And the Child form
public partial class Kit : Form
{
private int _KitId=0;
private KitTypes _parentForm = null;
public Kit(KitTypes parentForm)
{
_parentForm =parentForm;
}
}
And from your First form, when you create an object of this, pass the parent form as the parameter
Kit objChild=new kit(this);
objChild.Show();
Now in your child, form you can call the public method of parent form like this
this._parentForm.ReloadData();