C# passing string between voids - c#

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.

Related

How to parse data from the firebase database to int

public void saveData()
{
Reference.Child("users").Child(userId).Child("level").SetValueAsync(levelText.text.ToString());
}
public void loadData()
{
FirebaseDatabase.DefaultInstance.GetReference("").ValueChanged += Script_ValueChanged;
}
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
levelText.text = e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true).ToString();
}
In this example I can load my level from the database and save it. My problem right now is I want to load the level from the database and store it in a Int level Variable so I can make a levelup function and update the level in the database. Does someone know how to do that?
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
level = (int)e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true);
levelText.text = level.ToString();
}
my idea was maybe doing it in that way, but inside unity It gives me an error message at that line:
"System.InvalidCastException: Specified cast is not valid."
You need to parse the int from the string, because a string cannot be cast to an int. You can use int.Parse() for that if you know that it contains a valid integer:
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
level = int.Parse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true));
levelText.text = level.ToString();
}
Documentation for int.Parse(): https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-7.0
Alternatively, you can also use int.TryParse() if you're not 100% certain that the string contains a valid integer:
private void Script_ValueChanged(object sender, ValueChangedEventArgs e)
{
if(int.TryParse(e.Snapshot.Child("users").Child(userId).Child("level").GetValue(true), out int parsedInt))
{
level = parsedInt;
}
levelText.text = level.ToString();
}
Documentation for int.TryParse():
https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-7.0
Another solution would be to use Convert.ToInt32() instead of int.Parse(), but it will do the same thing:
https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-7.0

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

C#. I keep getting an error stating I have "use of an unassigned local variable 'fullname'" [duplicate]

This question already has answers here:
Stuck in function and booleans
(2 answers)
Closed 5 years ago.
//I have to create a program that determines if the name is written in the correct format, then once it deems it correct it separates the first and last name.
public partial class nameFormatForm : Form
{
public nameFormatForm()
{
InitializeComponent();
}
private bool IsValidFullName(string str)
{
bool letters;
bool character;
bool fullname;
foreach (char ch in str)
{
if (char.IsLetter(ch) && str.Contains(", "))
{
fullname = true;
}
else
{
MessageBox.Show("Full name is not in the proper format");
}
}
return fullname;
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearScreenButton_Click(object sender, EventArgs e)
{
exitButton.Focus();
displayFirstLabel.Text = "";
displayLastLabel.Text = "";
nameTextBox.Text = "";
}
private void formatNameButton_Click(object sender, EventArgs e)
{
clearScreenButton.Focus();
}
}
Always remember these 3 rules for C#:
To use a variable, it must be initialized.
Field members are initialized with a default value
Locals are NOT initialized with a default value.
You are breaking rule 1: Using fullname before it is initialized. The following program will clarify this:
public class Program
{
public static void Main()
{
// This is a local and NOT initialized
int number;
var person = new Person();
Console.WriteLine(person.age); // This will work
Console.WriteLine(number); // This will not work
Console.Read();
}
}
public class Person
{
// This is a field so it will be initialized to the default of int which is zero
public int age;
}
To fix your issue, you need to initialize fullname:
bool fullname = false;
I would rename the variable to a more readable name such as isFullName.
Declaring a variable with no initial value and then returning it in a method with an if statement that does not determine the value doesn't make any sense. You have to assign a value to fullname if you want to return its value.
Init this variable first:
bool fullname = false;

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

Variable not being seen in C# code

Learning C# and hit a snag.
Why isn't the variable 'number' used here?
public partial class Form1 : Form
{
static string labelText = "";
static string number = "";
public Form1()
{
InitializeComponent();
}
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
I keep getting a warning that field 'number' is assigned but not used.
string number = this.serialNumber.Text; this line creates a new string.
try this to avoid the warning
public partial class Form1 : Form
{
static string labelText = "";
static string number = "";
public Form1()
{
InitializeComponent();
}
private void serialNumber_TextChanged(object sender, EventArgs e)
{
number = this.serialNumber.Text;
}
string number declares a new local variable which hides the static member variable.
Change these lines:
static string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
string number = this.serialNumber.Text;
}
to
private string number = "";
private void serialNumber_TextChanged(object sender, EventArgs e)
{
number = this.serialNumber.Text;
}
In your serialNumber_TextChanged method you declare a local variable called number. So if that is your complete code you never actually assign anything to Form1.number apart of the static initialization.
That's exactly what's happening: you are assigning a value to the variable number, and then you don't do anything with that variable.
First off, the warning is valid, and relates to the static member, which, in fact, is assigned and never used. The one in serialNumber_TextChanged is local to that method and by definition, different.
This: "Why isn't the variable 'number' used here?"...I do not understand.
It happens because of the string in the instruction string number = this.serialNumber.Text;, which is declaring a new variable, different from the class field, despite having the same name. Remove the string modifier and the instruction will refer to the class field already declared.

Categories