I know this is a basic question, but I am struggling with it for quite some time now..
I have a main form in which I have a List<Filenames> and I have another class that gets invoked by the main form. This class has to insert some entries in my List<Filenames>.
In main form, I have the list initialized as:
public List<Filenames> filenamesList = new List<Filenames>();
And in the other class I do:
MainForm mainForm = new MainForm();
mainForm.filenamesList.Clear();
//then I have a for loop in which I perform some changes
mainForm.filenamesList.Add(new Filenames { name = "filename1", id = 1 } );
//it works until here and a new Filenames is added to the list
//then we go back to the main form
The problem is that now the List<Filenames> is empty. What am I doing wrong?
I have another class that gets invoked by the main form
I suspect the problem is here:
MainForm mainForm = new MainForm();
This creates a new MainForm instance, which is not the same instance as the MainForm that invokes the function.
I would redesign this so that the function you are invoking returns a List<Filenames> (or just an IEnumerable<Filenames> to be less specific) and let the form class worry about filling its filenamesList property. Exposing data members of a form can get messy quickly since you need to pass an instance of the form to anything that must use the property.
soimething like this:
-- other class --
public IEnumerable<Filenames> GetFilenames()
{
return new List<Filenames> { new Filenames { name = "filename1", id = 1 } };
}
--MainForm--
this.filenamesList.Clear();
this.filenamesList.AddRange(otherclass.GetFilenames());
When you do this in the second form:
MainForm mainForm = new MainForm();
You've created an entirely new instance of MainForm that has no reference to the list in the original MainForm instance. You're clearing the list and adding items to it, but when you exit your second form those items are lost.
You've got to pass your original MainForm instance to the new form that opens:
public class Form2 : Form
{
private MainForm mainForm;
public Form2(MainForm mainForm)
{
this.mainForm = mainForm;
}
public void SomeMethodThatUpdatesFileNamesList()
{
mainForm.filenamesList.Clear();
...
}
}
By declaring a new MainForm using the line MainForm mainForm = new MainForm(); you are not referring to the same filenamesList. You need to get the reference to the first class, either by sending the filenamesList as a parameter to the function or by adding it as a propery in one of the classes.
If the "other class" is a child of the main form, you might be able to get a reference to the parent object, but this depends on the stucture of the program.
Related
I have a main form and I need in other class get or set field from Main Form. I created public property in Main Form:
public partial class MainForm : Form
{
public string get_txt()
{
return phone.Text; //phone - textbox
}
}
But in other class I can't get this property:
MessageBox.Show(MainForm.get_txt); //there error. It doesn't seemed get_txt property.
I'm sorry for this simpliest question, but I really don't know this. Everywhere wrote that simpliest way to do it - in class of Main Form create public property for needed private field in Main Form. What do I wrong?
So the MessageBox.Show(MainForm.get_txt) won't compile as you're trying to refer to a static property, not an instance method.
I'm not a winforms dev, so this is a bit of a guess:
Somewhere in your code you will have a call like var main = new MainForm(). On that instance i.e. main you will be able to call main.get_txt().
As a side note, given that you're working in C# it'd be good to name the method to something a little more idiomatic, perhaps public string GetPhoneNumber() or better yet make it a property:
public string PhoneNumber
{
get { return phone.Text; }
}
Make instance of MainForm and than call it.
Mainform _mainform=new Mainform();
MessageBox.Show(_mainform.Get_text);
Your MainForm is not static class, you can not use like that. If u want access the MainForm(methods or variables), you have to assing the variable.
MainForm mForm = new MainForm();
MessageBox.Show(mForm.getText());
Thanks to you all.
but when I create a new istance of Main Form all controls in it will be initializing like in my current Main Form?
In my main form's constructor i have:
itemDisplay newForm = new itemDisplay();
newForm.Show();
elsewhere in the form i have a textbox_textchanged event where i am trying to reference a method in newForm but it won't let me access the instance much less the methods within it. The constructor is public what else am i missing?
You need to keep a reference to the newly created form as a module-level variable. Something like this:
private itemDisplay newForm = new itemDisplay();
public my_main_form()
{
newForm.Show();
}
Then you should able to access newForm anywhere from in the main form.
You can also create instance of class below
private itemDisplay newForm;
public my_main_form()
{
newForm = new itemDisplay();
newForm.Show();
}
I am using two forms in a windows form application in C#.I want to pass the tabControl's properties like its "Tabpage count" from first form to second form. Can anyone help me here?I can't create object of first form in second form and call a function beacuse for a new forn object, the tabcontrol gets refreshed.
Inside your first form create an instance of your second Form class as this
Form frm= the instance of your secand form
after that show the instance of your secand form, now you exactly have an instance of your secand form inside your first form and can use all the public properties of it
You can create static public functions exposing desired control properties like in below code.
public static Color TabColor()
{
return Form1.Fom1TabControl1.SelectedTab.ForeColor;
}
and you can access Form1 properties like below;
private void Form2_Load(object sender, EventArgs e)
{
this.Fom2TabControl1.SelectedTab.ForeColor = Form1.ForeColor;
}
First Check your class accessibility and set to public if not work set public static, maybe your namespaces is different
hope it helps
This can be achieved in two ways
Aprroach 1:
Create a public variable in Form2
public int intTabCount=0;
and in Form1, you should call Form2 like
Form2 objForm2 = new Form2();
objForm2.intTabCount = tabPageCountVariable;
objForm2.Show()
Aprroach 2:
Create a parameterized constructor and public variable in Form2
public int intTabCount=0;
public Form2(int TabCounts)
{
intTabCount = TabCounts; // and use intTabCount for your class
}
and call from Form1 like
Form2 objForm2 = new Form2(tabPageCountVariable);
objForm2.Show();
Now if you want to pass value through any events like clicking an button in Form1 which updates anything in Form2, use the below link
Passing Values Between Windows Forms c#
I have 9 buttons in Form1.Designer.cs and I want to access them in another class, Puzzle.cs because later on I need to modify button changes in model class. The code below is what I attempted.
private Button[,] buttons = new Button[3, 3]
{ { Form1.button1, Form1.button2, Form1.button3 },
{ Form1.button4, Form1.button5, Form1.button6 },
{ Form1.button7, Form1.button8, Form1.button9 } };
It fails as the modifier for buttons is not static. I changed them into static type but this causes errors for buttons.
Can anyone give some advice?
You need a reference to an instance of the Form1 class. If it were called form, you could then access the button like form.button1.
But I'm not sure accessing buttons of the form from another class is a good design.
To get things compiling correctly, you'll need to make the following changes:
public partial class Puzzle : Form
{
private Button[,] buttons;
public Puzzle(Form1 form1)
{
buttons = new Button[,]
{
{ form1.Button1, form1.Button2, form1.Button3, },
{ form1.Button4, form1.Button5, form1.Button6, },
{ form1.Button7, form1.Button8, form1.Button9, },
}
};
}
The idea here is that Form1 is a class, not an instance of a class... A class is like a blueprint of a house, and a house is like an instance of that blueprint.
To get furniture out of the house, you first must instantiate and initialize that house (build, if you will), and then access the house's furniture instances.
In this case, you'll need to instantiate a new Form1, and pass that to the Puzzle form's constructor.
Form1 myForm = new Form1();
Puzzle myPuzzle = new Puzzle(myForm);
Puzzle will now be able to access that instance of Form1's buttons.
Note:
You can find the Program's instance of Form1 by looking in the Program.cs file of your solution.
Yesterday I asked a question how it is possible to access my mainform from another form to give it the focus.
Giving focus back to main form
The solution was to add a reference to the mainform when the new form is called.
This works great for .focus() by doing:
Form mainform_instance;
public NewForm(Form mainform)
{
this.mainform_instance = mainform;
InitializeComponent();
}
However now I need to access a 'custom function' on the main form from my new form.
But I cannot access it since it is declared as Form mainform_instance and the Form type doesn't have my custom function. (at least that's what I think what goes wrong.)
So I thought I try:
MainForm mainform_instance;
and
Namespace.MainForm mainform_instance;
But both don't work.
How can I access my function (foo()) on the mainform from the new form?
EDIT
As requested by Adam Maras in comment:
namespace Namespace
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
EDIT2
MainForm code which calls the NewForm:
newForm = new Namespace.NewForm(this);
newForm.Show();
NewForm construct:
namespace Namespace
{
public partial class NewForm : Form
{
// here I tried to do MainForm mainform_instance as well as in the construct param
Form mainform_instance;
public NewForm(Form mainform)
{
this.mainform_instance = mainform;
InitializeComponent();
}
In the NewForm objects Load event, this.Owner would return your main form object if you invoked NewForm with a ShowDialog(this) call.
// in your MainForm
NewForm nwForm = new NewForm();
nwForm.ShowDialog(this);
// inside your NewForm object, after loading
(this.Owner as MainForm).Foo();
I realize I misdirected you in your previous post by asking you to use this.Parent(); I should have remembered it is this.Owner(). Apologies!
If you know exactly what kind of form type to use, simply change the code to reference that kind of form.
MainForm mainform_instance;
public NewForm(MainForm mainform)
{
this.mainform_instance = mainform;
InitializeComponent();
}
If you can have multiple types of forms then you can try to cast it to MainForm prior to using it, and if successful - use it.
MainForm mainForm = mainform_instance as MainForm;
if (mainForm != null) mainForm.foo();
Make the custom function public and pass the reference of main form to the new form. Then using the main form's reference you will be able to call any public method of main form from new form
Is your function declared private?
I never recommend a main form reference to any other form ...there is always a better way. That said, if you have a method that needs to be executed from the form, you must pass a reference to that main form method.
public NewForm(Form mainform, Action mainFormMethod)
{
this.mainform_instance = mainform;
InitializeComponent();
mainFormMethod.Invoke(); // or just mainFormMethod();
}
See MSDN: Action Delegate
There is also the Action<T> ...be sure and check those out. If your method requires a return, you will need to check out Func<TResult>
For the records, I would recommend re-thinking sending the reference to the main form.