Pass along global variable to class - c#

I am trying to pass a string to a public class (customPanel).
But the "teststring" is never passed on and written to the testfile.txt?
The testfile.txt writes an empty string.
private void button1_Click(object sender, EventArgs e)
{
customPanel cp = new customPanel();
cp.getinfo = "teststring";
}
public class customPanel : System.Windows.Forms.Panel
{
public String getinfo { get; set; }
public customPanel() { InitializeComponent(); }
private void InitializeComponent()
{
String gi = getinfo;
System.IO.FileStream fs = new System.IO.FileStream("C:/folder1/testfile.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
System.IO.StreamWriter writer = new System.IO.StreamWriter(fs);
writer.WriteLine(gi); writer.Close(); fs.Close();
}
}

The problem you’re having is happening because of the order of execution of your code.
Basically when you call new customPanel(), that’s when the constructor method controlPanel() is going to be called. So when you set the getInfo value, your InitializeComponent() method was already called.
Without knowing better about your context, the easy solution would be to pass the string as a parameter to your constructor. Basically switch controlPanel() to receive a string variableName as a parameter, like this controlPanel(string variableName)and then before calling InitializeComponent(); set the value of the property with a this.getInfo = variableName;.
Let me know if this helped!
Take care.

Related

Access RichTextBox from another class

I am new and trying to do something in c# but I dont know how to solve this prbolem.
My MainWindow.xaml.cs I have a RichTextBox with name RTB that I wanna save into text file.
I created new file Saving.cs where I would write every thing that I need for saving.
This is my code.
Saving.cs
public string VarName = "";
public void Save()
{
MainWindow main = new MainWindow();
TextRange range = new TextRange(main.RTB.Document.ContentStart, main.RTB.Document.ContentEnd);
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
MainWindow.xaml.cs
private void Button_Save(object sender, RoutedEventArgs e)
{
saveDoc.VarName = SaveName.Text + ".txt";
saveDoc.Save();
}
Everything works fine except that there is nothing in saved document.
My problem is that I really dont know how to acces RTB from different file. It works when I put this code into MainWindow.xaml.cs but not when its in different file like Saving.cs.
I also dont know if its ok to have this in my Saving.cs "MainWindow main = new MainWindow();" or how to aproach this problem.
Thanks for your help kind stranger.
I hope these code snippets can help to solve your problem
MainWindow.xaml.cs :
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
TextRange range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd);
//You can pass this 'range' field as a parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
Saving.cs :
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(TextRange range)
{
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
}
Also you can do like this:
MainWindow.xaml.cs :
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
string range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd).Text;
//You can pass this 'range' field as parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
Saving.cs :
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(string range)
{
// Standart algorithm to write something in file:
FileStream stream = new FileStream(VarName, FileMode.Create);
//convert string to bytes
byte[] buf = Encoding.Default.GetBytes(range);
// writing an array of bytes to a file
stream.Write(buf, 0, buf.Length);
stream.Close();
}
}

Calling functions between different classes

I am used to writing embedded c and poorly skilled in c#.
My problem is that I want to be able to run the function openAnotherForm() from Welcome_Form and right now the code does not work. I patiently tried different things but only managed to push my frustration.
I simplified my relevant code to illustrate the problem.
File 1 - This will run and open file 2.
class UIcode
{
private Welcome_Form Welcome;
private AnotherForm_Form AnotherForm;
public UIcode()
{
Welcome = new Welcome_Form();
Application.Run(Welcome);
}
public void openAnotherForm()
{
Welcome.Hide();
AnotherForm = new AnotherForm_Form();
AnotherForm.ShowDialog();
}
}
File 2 - When I click TheButton, the program should run the function openAnotherFrom from file 1.
public partial class Welcome_Form : Form
{
public Welcome_Form()
{
InitializeComponent();
}
private void TheButton_Click(object sender, EventArgs e)
{
// Function from file 1
UIcode.openAnotherForm();
}
}
I realize the problem might be quite trivial but I would still be grateful for an explanation on how to do this.
Preferable: The functions from UIcode should only be recognized by classes specified by UIcode.
You can change the constructor to take a reference to the instance of UIcode that opened it:
private static UIcode myParent;
public Welcome_Form(UIcode parent)
{
myParent = parent;
InitializeComponent();
}
Now in UIcode:
public UIcode()
{
Welcome = new Welcome_Form(this);
Application.Run(Welcome);
}
And finally, back in Welcome_Form:
private void TheButton_Click(object sender, EventArgs e)
{
// Function from file 1
myParent.openAnotherForm();
}
Your openAnotherForm() method is not static, so it needs an instance reference in order to be used. Either instantiate a UICode object, or mark the method as static.
You to create an instance of the class in File1 to call the method. You've called the class UICode, so the constructor should be renamed from public UserInterface() to public UICode().
class UIcode
{
private Welcome_Form Welcome;
private AnotherForm_Form AnotherForm;
public UIcode() // Renamed Constructor
{
Welcome = new Welcome_Form();
Application.Run(Welcome);
}
public void openAnotherForm()
{
Welcome.Hide();
AnotherForm = new AnotherForm_Form();
AnotherForm.ShowDialog();
}
}
public partial class Welcome_Form : Form
{
public Welcome_Form()
{
InitializeComponent();
}
private void TheButton_Click(object sender, EventArgs e)
{
// Create an instance UICode
UICode instance = new UICode();
// Call the method from the instance, not from the class.
instance.openAnotherForm();
}
}
Alternatively, you can make openAnotherForm() a static method, but you'll also need to make the instance variables (Welcome and AnotherForm) static. You will also need to initialize them, but you can do that by making the constructor static as well.
class UIcode
{
private static Welcome_Form Welcome;
private static AnotherForm_Form AnotherForm;
public static UIcode() // Renamed Constructor
{
Welcome = new Welcome_Form();
Application.Run(Welcome);
}
public static void openAnotherForm()
{
Welcome.Hide();
AnotherForm = new AnotherForm_Form();
AnotherForm.ShowDialog();
}
}

Utillize string filename from form1 to form 2

In form 1 I have open an xml file. Now I want to able to use the string filename in Form2 so I am able to do extra feature and/or use what inside the file.
Form1
DialogResult result;
string filename;
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
}
}
Form2
namespace PreviewForm
{
public partial class Preview : Form
{
int ind1 = 1;
public Preview()
{
InitializeComponent();
}
private void Preview_Load(object sender, EventArgs e)
{
//I want to able to do something like this
//XmlDocument xDoc = new XmlDocument();
//xDoc.Load(filename);
//foreach(XmlNode xNode in xdoc.SelectNode(People/People))
//{
// Label lable1 = new Label();
// label1.Text = xNode.SelectingSingleNode("Name").InnerText;
// label1.Name = "label_" + ind1;
// label1.Location = new Point(code);
// ind1++;
// this.Controls.Add(label1);
}
}
}
So I want to able to use the string filename in form1 to form2.
Just use a private field instance and add it to the constructor
namespace PreviewForm
{
private string _filename = string.Empty;
public partial class Preview : Form
{
int ind1 = 1;
public Preview(string filename)
{
InitializeComponent();
_filename = filename;
}
to use the string filename in Form2
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
//for example here
PreviewForm form2=new PreviewForm(filepath);
form2.ShowDialog(this);
}
}
Solution 1 : You can send the FilePath from Form1 to the Form2 using constructor as below:
Form2 form2=new Fomr2(filepath);
form2.ShowDialog();
and create a string parameter constructor in Form2 as below:
string filepath;
public Preview(string filepath)
{
InitializeComponent();
this.filepath=filepath;
}
Solution 2: Make the filepath variable as public static in Form1 so that it can be accessible using its classname.
Try This:
public static string filepath;
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
Form2 form2=new Fomr2(filepath);
form2.ShowDialog();
}
}
From Form2 :
You can access from as below:
String filepath = Form1.filepath;
Some have already posted working examples, but I'd like to give you a general overview of what can be done when you need to pass data from a class to another one.
I'm presenting you with 3 basic ways to pass your data from the first class (the sender class) to the second (the receiver class):
Constructor Injection. This is what most people have described here, and it basically mean to have a "special" constructor on your receiver class that will be called from the sender class to pass the necessary data as a parameter when the receiver class object is instantiated. The data can then be saved to a local member on the receiver class.
Setter Injection. In this case, you define a public property on the receiver class that you call from the sender class, but after the receiver has been instantiated. As with the constructor injection, you can save the data to a local member on the receiver.
Method Injection. In this case, you define a method on the receiver class that will have a parameter defined to receive the data. here you can either decide to store the data to a member of the receiver, but you could also decide to use the data directly in the method body and discard it when done.
This is by no mean an exhaustive list of how you can pass data between classes, but it will give you a good starting point.
Cheers

I cant call my method from class in form

Im new to c# and programming
i can make the method Work, but not when i try to call it from my class 'Admin', it think its just a minor problem, but im just stuck ... Again.. No overload for method "opretspejder" takes 0 arguments
any help help i would be glad
Here my class
public class Admin
{
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt)
{
{
if (!(string.IsNullOrEmpty(Snavn_txt)))
if (!(string.IsNullOrEmpty(Senavn_txt)))
if (!(string.IsNullOrEmpty(Sa_txt)))
if (!(string.IsNullOrEmpty(Scpr_txt)))
{
XmlDocument doc = new XmlDocument();
doc.Load(#"Spejder.xml");
var nodeCount = 0;
using (var reader = XmlReader.Create(#"Spejder.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Spejder")
{
nodeCount++;
}
}
}
nodeCount++;
XmlElement Spejder = doc.CreateElement("Spejder");
Spejder.SetAttribute("ID", nodeCount.ToString());
XmlNode Navn = doc.CreateElement("Navn");
Navn.InnerText = Snavn_txt;
Spejder.AppendChild(Navn);
XmlNode Efternavn = doc.CreateElement("Efternavn");
Efternavn.InnerText = Senavn_txt;
Spejder.AppendChild(Efternavn);
XmlNode Alder = doc.CreateElement("Alder");
Alder.InnerText = Sa_txt;
Spejder.AppendChild(Alder);
XmlNode Cpr = doc.CreateElement("Cpr");
Cpr.InnerText = Scpr_txt;
Spejder.AppendChild(Cpr);
doc.DocumentElement.AppendChild(Spejder);
doc.Save(#"Spejder.xml");
Snavn_txt = String.Empty;
Senavn_txt = String.Empty;
Sa_txt = String.Empty;
Scpr_txt = String.Empty;
// MessageBox.Show("Spejder Oprettet");
}
}
and here is the buttonclick i want to execute my method:
private void button2_Click(object sender, EventArgs e)
{
Admin.OpretSpejder();
}
The declaration of your method says
public static void OpretSpejder(string ..., string ...., string ...., string ....)
but you call it without passing any of the 4 strings required
Admin.OpretSpejder();
Of course the compiler is not happy
It seems that the method OpretSpejder wants to create an XML file with 4 elements and these 4 elements are required because without them the whole block of code is skipped, so you have no alternative than passing the 4 strings required
If you are the author of OpretSpejder then I think that you should know what to pass at the calling point, otherwise you should ask the author of the code what are these four parameters
You've declared OpretSpejder method with 4 mandatory string arguments
(Snavn_txt, Senavn_txt, Sa_txt, Scpr_txt):
public class Admin {
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt) {
...
So If you want to call this method you should either provide these arguments:
private void button2_Click(object sender, EventArgs e) {
string Snavn_txt = "..."; // <- Put your real values here
string Senavn_txt = "...";
string Sa_txt = "...";
string Scpr_txt = "...";
Admin.OpretSpejder(Snavn_txt, Senavn_txt, Sa_txt, Scpr_txt);
}
or as compiler suggested create an overload version of OpretSpejder with no arguments:
public class Admin {
// New overloaded version
public static void OpretSpejder() {
...
}
// Old version
public static void OpretSpejder(string Snavn_txt, string Senavn_txt, string Sa_txt, string Scpr_txt) {
...
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
Admin classAdmin = new Admin();
private void button2_Click(object sender, EventArgs e)
{
classAdmin.OpretSpejder("yourstring1","yourstring2","yourstring3","yourstring4"); //Admin.OpretSpejder();
}
}

String to event

I'm trying to programmatically call a function with event.
How to convert string to a event in general? My problem is actually not knowing How to do this?
How to convert str to event?
str = "test1";
// UserControlsBackgroundEventArgs = EventArgs
EventArgs arg = (EventArgs)str; --> ?
UserControlsBackgroundOutput(str);
//function
private string CLICKNAME = "test0";
private void UserControlsBackgroundOutput(EventArgs e)
{
if (CLICKNAME == e.output)
return;
if (e.output == "test1"){}
}
Error solved:
I had to do
UserControlsBackgroundEventArgs arg = new UserControlsBackgroundEventArgs(CLICKNAME);
instead of
UserControlsBackgroundEventArgs arg = new (UserControlsBackgroundEventArgs)(CLICKNAME);
i've written a code that mimic you code, hopefully you will find it useful:
public class UserControlsBackgroundEventArgs
{
public string output;
public UserControlsBackgroundEventArgs(string up)
{
output = up;
}
}
public delegate void UserControlsBackgroundOutputHandle(UserControlsBackgroundEventArgs e);
public class testEvent
{
public event UserControlsBackgroundOutputHandle UserControlsBackgroundOutput;
public void DoSomeThings()
{
// do some things
if (UserControlsBackgroundOutput != null)
{
string str = "test1";
UserControlsBackgroundEventArgs arg = new UserControlsBackgroundEventArgs(str);
UserControlsBackgroundOutput(arg); // you've done that with str, whitch makes me
// you don't know what the event param is
}
}
}
public class test
{
private testEvent myTest;
private const string CLICKNAME = "whatever"; // i don't know what you want here
public test()
{
myTest = new testEvent();
myTest.UserControlsBackgroundOutput += UserControlsBackgroundOutput;
}
void UserControlsBackgroundOutput(UserControlsBackgroundEventArgs e)
{
if (CLICKNAME == e.output)
return;
if (e.output == "test1")
{
}
}
}
Your event class needs to have a constructor accepting a string. Then you will be able to create a new event instance using a string. You can't "convert" a string to an instance of the event class. If the event class comes from a library or sth and doesn't have a string constructor, you can subclass it, implement a string constructor and override the output property.
If you want this kind of conversion to be possible, you have to use an explicit operator:
public static explicit operator UserControlsBackgroundEventArgs(string s)
{
var args = new UserControlsBackgroundEventArgs();
args.output = s;
return args;
}
This is only possible with a new class, not with EventArgs, because you can't change the code of that class.
Your UserControlsBackgroundEventArgs Implementation could provide implicit/explicit casts.
Take a look at implicit keyword documentation
However, the answer from Wojciech Budniak is better.

Categories