I cant call my method from class in form - c#

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();
}
}

Related

How can the scope be changed in a WinForms app to carry variables from a method to an object sender?

I am trying to carry the variables from the array over to the button click action. I can't find the way to set the scope to allow for this to work.
I have tried changing the modifiers to public, private, static, void, string, string[] etc.
I have also made all of the objects in the WinForms app set to Public
public partial class AutoPay : Form
{
public AutoPay()
{
InitializeComponent();
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
dateAndTime = DateTime.Now.ToString();
fileNumber = txtFileNumber.Text;
string[] headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(headerArray[0], headerArray[1]);
}
}
the headerArray[0] under the BtnSave_Click action has the red line under it showing that it is outside of the scope.
Try declaring the headerArray as a Property of the class
As was mentioned... you need to declare the headerArray outside the method... Also... it looks like you are trying to add information to the array before the array has information... try it this way(there are many other ways to do this too ;) ):
public partial class AutoPay : Form
{
private string[] headerArray; // <-- declare it here...
public AutoPay()
{
InitializeComponent();
headerArray = new string[2]; // <-- sometimes the normal way to initialize...
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(DateTime.Now.ToString(), txtFileNumber.Text);
}
}
or
public void HeaderInformation()
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = DateTime.Now.ToString();
headerArray[1] = txtFileNumber.Text;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation();
}

MessageBox doesn't show the variable

I have a list variable and I created an iterator for it to print out its content. It's working in the console application but when i try to do it using windows form(gui) it doesn't work
PROGRAM.CS
namespace gui
{
static class Program
{
public class studentdata
{
public string id, name, password, academicyear, finishedcourseslist, ipcourseslist;
public int noCoursesF, noCoursesIP;
public List<string> coursesF;
public List<string> coursesIP;
public studentdata()
{
id = "2015123";
password = "Student";
coursesF = new List<string>();
coursesIP = new List<string>();
}
public studentdata(string ID, string NAME, string PASSWORD)
{
id = ID;
}
**public void view_finished_courses()
{
List<string> finished = coursesF;
foreach (string n in finished)
{
finishedcourseslist += n;
}
MessageBox.Show(finishedcourseslist, "Finished courses");
}
public void view_ip_courses()
{
List<string> progress = coursesIP;
foreach (string m in progress)
{
ipcourseslist += m;
}
MessageBox.Show(ipcourseslist, "Finished courses");
}**
}
public class Admin
{
public string name, password;
public Admin()
{
name = "Admin";
password = "Admin";
}
}
//functionssssss
internal static studentdata studentSearch(string IDsearch)
{
FileStream FS = new FileStream("Students.txt", FileMode.Open);
StreamReader SR = new StreamReader(FS);
studentdata std = new studentdata();
while (SR.Peek() != -1)
{
string z = SR.ReadLine();
String[] Fields;
Fields = z.Split(',');
if (IDsearch.CompareTo(Fields[0]) == 0)
{
std.id = Fields[0];
std.password = Fields[1];
std.name = Fields[2];
std.noCoursesF = int.Parse(Fields[3]);
int currentField = 4;
for (int course = 0; course < std.noCoursesF; course++)
{
std.coursesF.Add(Fields[currentField]);
currentField++;
}
std.noCoursesIP = int.Parse(Fields[currentField]);
currentField++;
for (int course = 0; course < std.noCoursesIP; course++)
{
std.coursesIP.Add(Fields[currentField]);
currentField++;
}
std.academicyear = Fields[currentField];
SR.Close();
return std;
}
else continue;
}
SR.Close();
studentdata araf = new studentdata();
return araf;
}
}
FORM.CS
namespace gui
{
public partial class Form3 : Form
{
Program.studentdata student = new Program.studentdata();
public Form3()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
student.view_finished_courses();
}
private void button6_Click(object sender, EventArgs e)
{
student.view_ip_courses();
}
}
}
The output is an empty message box, I don't know why variable isn't added.
Replace messagebox line with
MessageBox.Show(string.Join(",", coursesF.ToArray()), "Finished courses");
It seems like your code is incomplete. Nowhere in the code which gets executed after you clicked button4 you are adding items to coursesF. It seems that you are adding items in this line: std.coursesF.Add(Fields[currentField]);
This line is in your function studentSearch(IDsearch), the function never gets called.
In this function you got a string z in which all the data of a student is saved (string z = SR.ReadLine()). You must somehow fill this string z. You can use a TextBox in your form and pass the value into the string, use a string from a text file or use the console input(see here: Get input from console into a form).
As you can see the issue is not a one line fix.

Passing string between forms returns null

In the program you enter with a username brought from a database. I need to pass that username to another form but when I do it, it returns null in the second form although in the first form it appears.( "Jugador" is the class from where I bring the name).
public Usuario()
{
InitializeComponent();
}
private string _Message;
public string Message
{
get { return _Message; }
set { _Message = strName; }
}
public string strName;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text!="")
{
Jugador jug = new Jugador();
jug.Traemelo(textBox1.Text);
strName = textBox1.Text;
elegirTipo us = new elegirTipo();
us.Show();
this.Hide();
}
}
And in my other form i have this.(Usuario is the first form)
private void silabas_Load(object sender, EventArgs e)
{
Usuario usu = new Usuario();
juga.Traemelo(usu.Message);
}
I've got to add that in the middle of these forms I pass by one but doens't need the variable there.
Thanks for the help! I really don't know what is happening because I've done this other times.
// Usuario.cs
public string Message { get; set; }
...
Silabas silabas = new Silabas(this);
// Silabas.cs
public Silabas(Usuario usuario)
{
// Here you can access the usuario.Message
}
What I personally would do is to create a static class and hold the values in it. This would also let me not to instantiate the class every time I need to use it.
public static class Jugador
{
//ctor if needed
public static string Username { get; set; }
}
Now, in your code where you both set or get the values of the username:
//login process
Jugador.Username = "some username";
//in application (get)
textbox1.Text = Jugador.Username;
I believe this is what you are looking for.
At a first glance:
public string Message
{
get { return _Message; }
set { _Message = value } // instead of strName;
}
no Message=something (set is never called)
_Message seems to compete with strName. One variable should be enough.
EDIT: Combined to this:
public Usuario()
{
InitializeComponent();
}
private string _Message;
public string Message
{
get { return _Message; }
set { _Message = value; }
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
Jugador jug = new Jugador();
jug.Traemelo(textBox1.Text);
Message = textBox1.Text;
elegirTipo us = new elegirTipo();
us.Show();
this.Hide();
}
}
Problem is since you are creating a new instance i.e. Usuario usu = new Usuario(); of the object in the other class, the value becomes null. I would use a static variable. In your Usuario class use
public static string strName{get;set;}
Now to set the value say Usuario.strName = textBox1.Text;
in your other class here say,
private void silabas_Load(object sender, EventArgs e)
{
juga.Traemelo(Usuario.strName);
}

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.

C# passing string between voids

All i want to do is pass a string from one void to another.
private void getFilename2()
{
if (textBox2.TextLength.Equals("0"))
{
}
else
{
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
string[] filename2 = last.Split('.');
}
}
private void button1_Click(object sender, EventArgs e)
{
getFilename1();
getFilename2();
string filez = filename2;
}
I know this doesn't work but I'm very unfamiliar with how to move strings around in voids.
You should replace your getFilename2 function with
Path.GetFileNameWithoutExtension(textBox2.Text)
Your best bet would be to use a class field/property, or a function that returns a value.
string filez = GetFilename2();
private string GetFilename2() {
{
if (textBox2.TextLength.Equals("0")) return "";
string inputString = textBox2.Text.ToString();
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
return last.Split('.');
}
You could pass the string by reference as a parameter to your functions
private void button1_Click(object sender, EventArgs e)
{
string fileName;
getFilename1(ref string fileName);
}
private void getFilename1(ref string fileName)
{
// Whatever you do with fileName here will be reflected in the other function
}
Let's start with the name of your method: getFilename2.
The prefix of "get" implies the method should have a return type
A more appropriate name may be SetFileName
I'm assuming there is a getFileName1 method that is retrieving the file name from textBox1 and has the exact same code as getFileName2, but uses textBox1 instead of textBox2. This would be a good place to refactor your code and create a common method that can be reused:
private string GetFileName(string str)
{
if (string.IsNullOrEmpty(str)) return string.Empty;
string last = str.Substring(str.LastIndexOf('\\') + 1);
return last.Split('.');
}
But, we can refactor again and just use a built-in .NET method:
private string GetFileName(string str)
{
return Path.GetFileNameWithoutExtension(str);
}
And now that there is a common method, we can re-use it as needed:
private void button1_Click(object sender, EventArgs e)
{
string filez = GetFileName(textBox2.Text);
}
Now we have a method of GetFileName(); all it is doing is calling a built-in .NET method of GetFileNameWithoutExtension(). So, instead of even having a method, we should just use the built-in .NET method for returning a file name:
private void button1_Click(object sender, EventArgs e)
{
string filez = Path.GetFileNameWithoutExtension(textBox2.Text);
}
Now, let's look at passing a string from one void to another. Typically, you'd want to do this with an internal field or property. Since I'm partial to properties, I'll use them as an example:
private string FileName1 {get; set;}
private string FileName2 {get; set;}
private void SetFileName1()
{
FileName1 = Path.GetFileNameWithoutExtension(textBox1.Text);
}
private void SetFileName2()
{
FileName2 = Path.GetFileNameWithoutExtension(textBox2.Text);
}
private void button1_Click(object sender, EventArgs e)
{
SetFileName1();
SetFileName2();
string filez1 = FileName1;
string filez2 = FileName2;
}
However, if you did not want to use internal fields or properties, you could set the values by ref as answered by Rachel
If you're passing strings around, ideally you should be explicitly passing them around. IE: make your functions take and/or return the values they'll work with, especially if the return values aren't intended to be used by anything but the code that calls getFilename2. If you can't do that, however, you can declare a private string filename1 = null; public string[] filename2 = null inside the class, but outside any of your methods.
If you go that route, make sure to remove any string filename1 or string[] filename2 from your methods, or you'll end up declaring a local variable with the same name (and never setting the instance variables).
You can store it in a class level variable. In that way it can be accessed by any function.

Categories