Accessing object created in different Window in WPF application - c#

I have created one window and declared 2 instances of my object, then I modified them and wanted to pass to another Window. My questions are:
How would i do that ?
(I can pass simple types such as string or int trough window constructor but passing my own object giving me an error (Inconsistent Accessibility parameter order is less accessible then method))
Does it have any connection with dataContext ?
Can anybody explain to me how I can achieve that (in the simplest possible way)? What are the correct ways to do that ?
Here is part of my code (everything is in one namespace):
public partial class Main_window : Window
{
Order myOrder = new Order();
Menu menu = new Menu();
public Main_window()
{ InitializeComponent() }
private void OpenSecondWindow(object sender, RoutedEventArgs e)
{
Second_Window SecondWindow = new Second_Window();
Second.ShowDialog();
}
}
// Second Window class
public partial class Second_Window : Window
{
public Second_Window(Order someOrder)
{ InitializeComponent(); }
}

Make sure that the Order type, and any other type you intend to inject the SecondWindow with, is defined as a public class:
public class Order { ... }
A non-public type cannot be part of the signature of a public method or constructor.

Related

Static referenced in another .cs file

I am overlooking something simple I think. I have a form with a checkbox. I need to know if the checkbox is checked in a different cs file/class to know whether to make a column header Option1 or Option2.
Form1 (Public partial class) code:
public bool Checked
{
get
{
return checkBox1.Checked;
}
}
In my Export1 class I have private void CreateCell1 that takes in the data to be exported (creating an excel file from a datatable). The section of code I can't get to work is:
if (Form1.Checked.Equals("true"))
{
newRow["Option1"] = date2;
}
else
{
newRow["Option2"] = date2;
}
I am getting -Error 1 An object reference is required for the non-static field, method, or property 'Matrix1.Form1.Checked.get'
What did I overlook?
Well, the problem here is exactly what the compiler is telling you. You need an object reference in order to access the property.
Allow me to explain.
In C#, by default, class members (fields, methods, properties, etc) are instance members. This means that they are tied to the instance of the class they are a part of. This enables behavior like the following:
public class Dog
{
public int Age { get; set; }
}
public class Program
{
public static void Main()
{
var dog1 = new Dog { Age: 3 };
var dog2 = new Dog { Age: 5 };
}
}
The two instances of Dog both have the property Age, however the value is tied to that instance of Dog, meaning that they can be different for each one.
In C#, as with a lot of other languages, there are things called static members of classes. When a class member is declared static, then that member is no longer tied to an instance of the class it is a part of. This means that I can do something like the following:
public class Foo
{
public static string bar = "bar";
}
public class Program
{
public static void Main()
{
Console.WriteLine(Foo.bar);
}
}
The bar field of the Foo class is declared static. This means that it is the same for all instances of Foo. In fact, we don't even have to initialize a new instance of Foo to access it.
The problem you are facing here is that, while Form1 is not a static class and Checked is not a static property, you are treating it as such. In order for what you are trying to do to work, you need to create an instance of Form1 and access that instance's Checked property.
Depending on how your program is structured, there are many ways of doing this. If Form1 is created in the scope where you are trying to access Checked, then this will be straightforward. If Form1 is what spawns the new scope, then common practice is to pass a reference to it in the constructor.
For example, if Form1 creates a new Form2 then we do the following:
public class Form2 : Form
{
private Form1 parent;
public Form2(Form1 parent)
{
this.parent = parent;
InitializeComponent();
}
}
And then you can access parent throughout Form2. Of course, depending on the structure of your program, the exact implementation will be different. However, the general pattern is the same. Pass the reference to Form1, from the scope it was created in, to the new class, and then access it from there.
One way or another, you need to access the specific instance of Form1 that you're trying to check.
A few ways to do this are:
Pass the instance to the class constructor
Setting a public property of the other class to the instance of the form
Pass the instance to the method directly
For example:
public class SomeOtherClass
{
// One option is to have a public property that can be set
public Form1 FormInstance { get; set; }
// Another option is to have it set in a constructor
public SomeOtherClass(Form1 form1)
{
this.FormInstance = form1;
}
// A third option would be to pass it directly to the method
public void AMethodThatChecksForm1(Form1 form1)
{
if (form1 != null && form1.Checked)
{
// Do something if the checkbox is checked
}
}
// This method uses the local instance of the Form1
// that was either set directly or from the constructor
public void AMethodThatChecksForm1()
{
AMethodThatChecksForm1(this.FormInstance);
}
}
This class would need to be instantiated by the instance form1 using one of these methods:
// Pass the instance through the constructor
var someOtherClass = new SomeOtherClass(this);
// Or set the value of a property to this instance
someOtherClass.FormInstance = this;
// Or pass this instance to a method of the class
someOtherClass.AMethodThatChecksForm1(this);

C# - Unable to add item to listview from method invoked from class

Im having a strange problem with my programme, whenever I call a method from another class, it doesnt work as expected. Basically, what I am trying to do is add an item to a listview, and the code is in a method, and I am trying to invoke that method from another class. Here is my code:
public class Main1
{
public void addItemToLV(string text)
{
listView1.Items.Add(text);
}
}
public class MainForm
{
Main1 m1 = new Main1();
m1.addItemToLV("test");
}
Any ideas why this is happening? Thanks.
Under normal circumstances, the controls on a form are declared as protected properties within the designer.cs file rather than public properties, so those controls will normally not be accessible to code outside of the form on which they are declared. This is intentional, as it encourages good object-oriented programming habits.
Rather than modifying a control directly from code that exists outside the form, a better practice is to declare public methods and properties within your form that can be called from outside code to manipulate the protected controls:
public class Main1
{
public static void Main()
{
var mainForm = new MainForm();
mainForm.AddItemToListView("test");
}
}
public class MainForm
{
public void AddItemToListView(string text)
{
listView1.Items.Add(text);
}
}
You could try to pass the ListView as an argument in the constructor and make the function return this ListView to your MainWindow.
public class Main1
{
private readonly ListView _lv;
public Main1(ListView listview)
{
_lv = listview;
}
public ListView addItemToLV(string text)
{
_lv.Items.Add(text);
return _lv;
}
}
I think your code sample is not enough but I am trying to guess the reason behind the issue and I think it is one of the following:
1.You are initialising your listView1 in the load event of Main1, and you are trying to show the form after calling the method. In that case you should call the method after showing the Main1 form.
2. Or simply you are trying to call the method on a different instance than the one displayed.

Communicating both ways between classes

A little background on my project:
I'm making a multi-form application, which consists of 1 mainform, and 6 childforms that can be called from the mainform, but only 1 childform can be active at a time. These childforms share certain parts of code, which I do not want to copy. To solve this, I have a codefile within the same namespace which holds the nessaccary code.
This codefile however, needs access to certain properties of the currently active childform.
My search has come down to using an interface to extract the needed information from the active childform.
My code is currently looking like this:
Interface:
public interface Interface1
{
TabControl tabControl_Buizen_
{
get;
}
TabPage tabPage_plus_
{
get;
}
}
Childform:
public partial class Childform : Form, Interface1
{
Interface1 dummy;
public TabControl tabControl_Buizen_
{
get { return this.tabControl_Buizen; }
}
public TabPage tabPage_plus_
{
get { return this.tabPage_plus; }
}
Methods_newTabPage methods = new Methods_newTabPage(dummy);
}
Codefile:
public class Methods_newTabPage
{
private readonly Interface1 form;
public Methods_newTabPage(Interface1 formInterface)
{
this.form = formInterface;
}
}
As you can see I'm using Methods_newTabPage methods = new Methods_newTabPage(dummy); to be able to call methods in my codefile, but the codefile requires the interface to be passed (which I filled as "dummy"). This however pops the error "A field initializer cannot reference the non-static field, method, or property Childform.dummy".
How can I let the childforms access the methods in the codefile, while also giving the codefile access to certain controls in differing childforms?
The error is easy to fix: just make dummy static.
static Interface1 dummy;
However, I don't think that will help you much. Why are you passing this dummy to Methods_newTabPage anyway? This will lead to NullReferenceExceptions inside the code file because dummy was never initialized with anything.
Don't you rather want to pass this, i.e. the current instance of Childform?
But you cannot just exchange dummy with this like so:
// Compiler error "Keyword 'this' is not available in the current context".
Methods_newTabPage methods = new Methods_newTabPage(this);
Instead you have to add a constructor that creates Methods_newTabPage:
public partial class Childform : Form, Interface1
{
private Methods_newTabPage methods;
public Childform()
{
methods = new Methods_newTabPage(this);
}
public TabControl tabControl_Buizen_ { get { return this.tabControl_Buizen; } }
public TabPage tabPage_plus_ { get { return this.tabPage_plus; } }
}
Try adding a constructor that initializes the field methods.
Also I don't see how that dummy makes sense. Instead initialize methods via methods = new Methods_newTabPage(this); in the constructor.

Error thrown :Form' does not contain a constructor that takes '1' argument. Any help or correction done to sort this error will be very thankful

public void PassValue(string CBA)
{
comboBox1.Text = CBA;
}
public void PassValueA(string CBB)
{
label14.Text = CBB;
}
private void button2_Click(object sender, EventArgs e)
{
Form8 Session = new Form8(comboBox1.Text);
Session.Show();
}
This means that Form8 is missing this:
public Form8(string text) { }
If you opened the code-behind for Form8 I bet you'd see this:
public Form8()
{
// you might even have some code in here
}
BUT, don't get rid of that one, leave it there. The designer will complain next if you do that. Build the one I gave you, and put your code there. Finally, depending on what the overload does, you might want to base one constructor on another, for example:
public Form8() : this("default value") { }
That would call the overloaded constructor from the default constructor and send a default value in for the string.
Now, there is a chance you want it to go the other way. No problem, you could do this:
public Form8(string text) : this() { }
Windows Form Class by default has Parameterless constructor. But You have define a constructor as follows to pass parameter from other forms or class.
public partial class Form8 : Form
{
public Form8(string info) {
//do something
}
}
Does Form8 have a constructor that has one parameter? Something like:
using System.Windows.Forms;
public partial class Form8 : Form
{
public Form8() // This parameterless constructor is required by the WinForms Designer
{
InitializeComponent();
}
public Form8(string someValue) : this() // Constructor chaining
{
// Do something with someValue here
}
}

Multiple .cs files and access to Form

I'm trying to write my first program in C# without the use of a tutorial. To ensure that I adopt from the start good coding practices, I want to create each class in an different .cs file. However, I'm running into some troubles when trying to access the elements of the program in such an .cs file.
For example, I have an Form1.cs with an Label and a Start button. When clicking on the start button, a text should appear in the Label. So:
In Form1.cs I have:
namespace TestProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void startButton_Click(object sender, EventArgs e)
{
WriteToLabel message = new WriteToLabel();
message.WelcomeMessage();
}
}
}
And in my separate WriteToLabel.cs file:
namespace TestProgram
{
public class WriteToLabel
{
public void WelcomeMessage()
{
Form1 myForm = new Form1();
//myForm.. --> myForm doesn't have an 'outputLabel'?
outputLabel.Text = "Welcome!"; // This returns an error: 'The name outputLabel does not exits in the current context'.
}
}
}
'outputLabel' is the (Name) I've given the label, and this is in accordance to the name in Form1.Designer.cs.
Both files are using the same components such as 'using System';.
However, from my WriteToLabel.cs file I can't seem to access the Form which holds my program. I did manage to succeed to create different .cs files in an Console Application, which only added to my confusion. So, I have two questions:
First, how can I access the Form from a separate class (i.e. not an partial class) in a separate file?
Second, is this the good way to do it, or is it inefficient to create multiple instances of different classes?
Any thoughts or ideas are highly welcome,
Regards,
The designer automatically creates controls as private fields, because of that your WriteToLabel class can't access it. You need to change that.
Also a good start would be to change the class to something like that:
namespace TestProgram
{
public class WriteToLabel
{
Form1 form;
public WriteToLabel(Form1 form)
{
this.form = form;
}
public void WelcomeMessage()
{
//Form1 myForm = new Form1();
//myForm.. --> myForm doesn't have an 'outputLabel'?
form.outputLabel.Text = "Welcome!";
}
}
}
You're actually instantiating a new instance of Form1, whereas you need to pass in a reference to your existing instance:
public void WelcomeMessage(Form1 form)
{
form.outputLabel.Text = "Welcome";
}
You also need to ensure that outputLabel is a public (or internal) property/field of Form1 so you can set the value accordingly. Then the calling code is slightly different:
private void startButton_Click(object sender, EventArgs e)
{
WriteToLabel message = new WriteToLabel();
message.WelcomeMessage(this);
}
You need to make sure that Form1.outputLabel has public or internal visibility.
You only need something like a LabelWriter class if the class is going to share a significant amount of state or private methods. If all you have is a bunch of methods that set properties on separate objects, you might as well just keep it as a method on the same object (in this case the Form1 object):
void startButton_Click(object sender, EventArgs e)
{
displayWelcomeMessage();
}
void displayWelcomeMessage()
{
this.outputLabel = "Welcome!";
}

Categories

Resources