Passing string between forms returns null - c#

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

Related

Passing Object from Class to Windows Form

I've got four main files in play here: Form 1, which is called frmLogin, Form2, which is called frmUserHome, a class called DbConnector.cs and a class called BankAccount.cs
The program works as follows: Form1 calls method from DBConnector -> DB Connector method fills an object and it's variables which is instantiated in DBConnector. This object is of class BankAccount.cs
Then, after the method finishes and if successful, Form1 instantiates Form2 and it opens. In form2 is where I want to access the object that was created in the DBconnector class. How do I do this? I've tried instantiating new objects of BankAccount.cs in there, I've tried all these different constructor stuff I've seen on here. Nothing seems to be working.
For reference: the object is populated when it runs in Dbconnector. However, when I try to receive data when I use it in Form2, all of the fields are NULL.
I've made countless adjustments from reading different posts on here so the code is rightfully a mess now and probably extremely unorganised.
Here's the main portions of my code below:
Form1
namespace BankingSystem
{
public partial class frmLogIn : Form
{
public BankAccount myBankAccount = new BankAccount();
dbConnector newConnector;
public frmLogIn()
{
InitializeComponent();
timerMain.Enabled = true;
timerMain.Start();
}
private void btnLogIn_Click(object sender, EventArgs e)
{
try
{
newConnector.CheckDetailsLogin(accountNumTextBox.Text, pinNumTextBox.Text);
frmUserHome UserHome = new frmUserHome();
MessageBox.Show("Success! Happy Banking!");
UserHome.ShowDialog();
}
catch
{
MessageBox.Show("Failed - incorrect login details.");
}
}
}
}
DBConnector Class:
namespace BankingSystem
{
public class dbConnector
{
Boolean isCorrect = false;
private static SQLiteConnection sqlconnConnection;
public BankAccount myBankAccount = new BankAccount();
public DataSet myAppDataSet = new DataSet(); // created for you to use and push data into
public dbConnector(string strFilePath)
{
try
{
sqlconnConnection = new SQLiteConnection("Data Source=" + strFilePath);
}
catch (Exception ex)
{
throw new Exception("DbConnector initialisation unsuccessful:\n" + ex.Message);
}
}
public void CheckDetailsLogin(string strAccno, string strPin)
{
// this is where check ou the boiler plate code and adjst to my APP.
try
{
DataTable dtUser = new DataTable();
sqlconnConnection.Open();
string strQuery2 = #"SELECT * FROM Accounts WHERE Account_Number='"+ strAccno +"' AND PIN='"+ strPin +"';"; // example of a parametrised SQL statement.
SQLiteCommand sqlcomCommand2 = new SQLiteCommand(strQuery2, sqlconnConnection);
SQLiteDataAdapter sqldatadptAdapter = new SQLiteDataAdapter(sqlcomCommand2); // local SQL data Adaptor
try
{
sqldatadptAdapter.Fill(dtUser);
}
catch (Exception ex)
{
// Exception will the "thrown"/Raised when there was a problem
throw new Exception($"SELECT unsuccessful:\n{ex.Message}");
}
finally
{
sqlconnConnection.Close();
}
if (dtUser.Rows.Count == 0)
{
// the record set comes back with no records found, an empty Datatable with no rows
// means there was no data matching your query
throw new Exception("No Such Bank user found");
}
else
{
// change to your applications needs
// Rows[0] - we are expecting at least 1 row, and its basically an array so we address
// the first element with 0
// Rows[0]["fieldnamefromDB"] <- referencing the column in the DB
//this.strID = strUserID;
myBankAccount.AccountNumber = dtUser.Rows[0]["Account_Number"].ToString();
myBankAccount.AccountPin = dtUser.Rows[0]["PIN"].ToString();
myBankAccount.AccountBalance = Convert.ToDecimal(dtUser.Rows[0]["Balance"]);
myBankAccount.AccountHolder = dtUser.Rows[0]["First_Name"].ToString();
myBankAccount.AccountAddress = dtUser.Rows[0]["Home_Address"].ToString();
myBankAccount.MyAccountGUID = dtUser.Rows[0]["GUID"].ToString();
if (myBankAccount.AccountNumber == strAccno && myBankAccount.AccountPin == strPin)
{
isCorrect = true;
}
else
{
isCorrect = false;
}
//myLocalBankAccUsr
}
}
catch (Exception ex)
{
// exception thrown for the whole method or function
throw new Exception($"User(string):\n{ex.Message}");
}
}
BankAccount.cs class
namespace BankingSystem
{
public class BankAccount
{
private string accountNumber;
private decimal accountBalance;
private string accountHolder;
private string accountPhoneNumber;
private string accountAddress;
private string accountPin;
private string myAccountGUID;
// private string AccountHolderGUID;
// private string AccountTypeGUID;
public string AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
public decimal AccountBalance
{
get { return accountBalance; }
set { accountBalance = value; }
}
public string AccountHolder
{
get { return accountHolder; }
set { accountHolder = value; }
}
public string AccountPhoneNumber
{
get { return accountPhoneNumber; }
set { accountPhoneNumber = value; }
}
public string AccountAddress
{
get { return accountAddress; }
set { accountAddress = value; }
}
public string AccountPin
{
get { return accountPin; }
set { accountPin = value; }
}
public string MyAccountGUID
{
get { return myAccountGUID; }
set { myAccountGUID = value; }
}
public Boolean CanWithDrawAmount(decimal AmountToTransfer)
{
if (AmountToTransfer > this.AccountBalance){
return false;
}else
{
return true;
}
}
public void UpdatePIN()
{
// connect to bank DB connector
// send it the new pin
// SQL update command
}
}
}
Here is Form2:
namespace BankingSystem
{
public partial class frmUserHome : Form
{
public frmUserHome()
{
InitializeComponent();
tabMainForm.Appearance = TabAppearance.FlatButtons;
tabMainForm.ItemSize = new Size(0, 1);
tabMainForm.SizeMode = TabSizeMode.Fixed;
timerMain.Enabled = true;
timerMain.Start();
}
private void frmUserHome_Load(object sender, EventArgs e)
{
labelWelcome.Text = "Welcome "; //newMainBank.AccountHolder;
}
The 'labelWelcome.Text = "Welcome" is where I want the name stored inside the object to be used. So it should ideally access the BankAccount class, access the AccountHolder field and use that field to concat onto the end of the 'Welcome' text. However, it just shows 'Welcome' and no name on the end, when I run the program (because all values get reset to null in form2.. for some reason)
Below I have updated the code for Form1 and Form2.
Form 1
namespace BankingSystem
{
public partial class frmLogIn : Form
{
dbConnector newConnector;
public frmLogIn()
{
InitializeComponent();
newConnector = new dbConnector(**pass str file path**);
timerMain.Enabled = true;
timerMain.Start();
}
private void btnLogIn_Click(object sender, EventArgs e)
{
try
{
newConnector.CheckDetailsLogin(accountNumTextBox.Text, pinNumTextBox.Text);
frmUserHome UserHome = new frmUserHome(newConnector.myBankAccount);
MessageBox.Show("Success! Happy Banking!");
UserHome.ShowDialog();
}
catch
{
MessageBox.Show("Failed - incorrect login details.");
}
}
}
}
Form 2
namespace BankingSystem
{
public partial class frmUserHome : Form
{ public BankAccount _bankAccount;
public frmUserHome(BankAccount bankAccount)
{
InitializeComponent(); _bankAccount = bankAccount;
tabMainForm.Appearance = TabAppearance.FlatButtons;
tabMainForm.ItemSize = new Size(0, 1);
tabMainForm.SizeMode = TabSizeMode.Fixed;
timerMain.Enabled = true;
timerMain.Start();
}
private void frmUserHome_Load(object sender, EventArgs e)
{
labelWelcome.Text = "Welcome "+ bankAccount.AccountHolder;
}

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

Converting Client String to Array on Server C#

I want to convert the string the server is receiving from the client to in an array. However when I use the String.Split method the result variable is showing null. Anyone know why that might be?
namespace ExampleLib.Server
{
public class Server
{
private class ConnectedClient
{
public int ID { get; }
private TcpClient _client;
private StreamReader _streamReader;
public delegate void NetDataEventHandler(object sender, NetDataEventArgs e);
public event NetDataEventHandler NetData;
public virtual void OnNetData(NetDataEventArgs e)
{
NetData?.Invoke(this, e);
}
public class NetDataEventArgs
{
public NetDataEventArgs(int id, string message)
{
ID = id;
Message = message;
}
public string Message { get; }
public int ID { get; }
}
public ConnectedClient(int id, TcpClient client)
{
ID = id;
_client = client;
}
private void ClientReceiveData(object sender, ConnectedClient.NetDataEventArgs e)
{
if (string.IsNullOrEmpty(e.Message) == false)
{
Trace.WriteLine($" Client {e.ID}: {e.Message}");
var result = e.Message.Split(',');
}
}
You have stopped at the break-point.
You should proceed one more step, in order for that line to be executed.
Currently, you're at a step similar to this.
If you proceed one more step using F10 (or 'Step Over' button) , it will execute that line and assign the value of addition to c in this example.

Windows Form Not Returning Correct Value from Public Method

I have three classes, code provided below.
Network - Add and Remove Phone, Process Calls
Phone1 and Phone2 can call each other when added to the network.
But I am having issue when I am connecting both phone to the network and trying to call phone1 to phone2, it is keep giving me "receiver busy". I have tried to do little debugging and read status of phone2 when calling from phone1 but it returns an empty string (Which should actually return "A", when it is added to the network).
Any help would much appreciated.
-----Networks Class------------------
namespace Demo
{
public partial class network : Form
{
phone1 p1 = new phone1();
phone2 p2 = new phone2();
public network()
{
InitializeComponent();
}
public Boolean numberValidator(int number)
{
Boolean exist = false;
if (comboBox2.Items.Equals(number))
{
exist = true;
}
return exist;
}
public void processCall(int rNumber)
{
if (!numberValidator(rNumber))
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Not connected";
//MessageBox.Show(p2.returnPhoenStatus());
}
else
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call in progress";
p2.receiveCall(1);
p1.setStatus("Busy");
/*
if (p2.btnCallPressStatus())
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call initiated";
}*/
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
p1.Show();
comboBox2.Items.Add(1);
p1.setStatus("A");
}
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
}
}
}
----------Phone1 Class---------
namespace Demo
{
public partial class phone1 : Form
{
public phone1()
{
InitializeComponent();
}
string status;
public void setStatus(string Status)
{
status = Status;
}
public string returnStatus()
{
return status;
}
public void receiveCall(int callerNumber)
{
setStatus("Busy");
btnCall.Text = "Answer";
textBox1.Text = "Phone " + callerNumber + " Calling.";
}
public void makeCall(int number)
{
phone2 p2 = new phone2();
network net = new network();
MessageBox.Show(p2.returnStatus()); // this line not returing status of phone2
if (p2.returnStatus() == "A")
{
net.processCall(number);
}
else
{
textBox1.Text = "Receiver Busy";
}
}
public TextBox TextBox1
{
get
{
return textBox1;
}
}
private void btnCall_Click(object sender, EventArgs e)
{
string number = textBox1.Text;
int numberInt = Convert.ToInt16(number);
makeCall(numberInt);
}
string phoneNo = "";
private void btn2_Click(object sender, EventArgs e)
{
phoneNo = phoneNo + btn2.Text;
textBox1.Text = phoneNo;
}
}
}
-------------phone2 Class--------------
namespace Demo
{
public partial class phone2 : phone1
{
public phone2()
{
InitializeComponent();
}
}
}
I think you are setting the status of P1 both the times. Check this if condition in button1_Click method in network class. The setStatus should be for P2.
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
Piyush has the right answer, but I thought I'd add this answer as a handy hint to avoid this kind of error.
Try writing your button1_Click method like this:
private void button1_Click(object sender, EventArgs e)
{
var i = comboBox1.SelectedIndex;
var p = (new [] { p1, p2 })[i]; // Or `var p = i == 0 ? p1 : p2;`
p.Show();
comboBox2.Items.Add(i + 1);
p.setStatus("A");
}
This way you avoid the code duplication and the mistyping that occurred.

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

Categories