Writing form state to xml C# - c#

My aim is to save the all form data via button click (as opposed to upon closing). To that end, I've used the example given in the following thread. Saving the form state then opening it back up in the same state
I've tried to adapt my code to the best of my ability, but nothing happens, and there are no errors shown. What am I doing wrong?
Here's the relevant parts of my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace WindowsFormsApplication1
{
public partial class frmPayroll : Form
{
SaveData sd = new SaveData();
public frmPayroll()
{
InitializeComponent();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
writeConfig();
}
private void writeConfig()
{
using (StreamWriter sw = new StreamWriter("config.xml"))
{
sd.Married = rdoMarr.Checked;
sd.PayPd = cbPayPd.Text;
sd.Allow = cbAllow.Text;
sd.Gross = txtGross.Text;
sd.Fit = txtFit.Text;
sd.Soc = txtSoc.Text;
sd.Med = txtMed.Text;
sd.NetPay = txtNet.Text;
sd.PayPd = cbPayPd.Text;
XmlSerializer ser = new XmlSerializer(typeof(SaveData));
ser.Serialize(sw, sd);
}
}
private void frmPayroll_Load(object sender, EventArgs e)
{
if (File.Exists("config.xml"))
{
loadConfig();
}
sd.Married = rdoMarr.Checked;
sd.PayPd = cbPayPd.Text;
sd.Allow = cbAllow.Text;
sd.Gross = txtGross.Text;
sd.Fit = txtFit.Text;
sd.Soc = txtSoc.Text;
sd.Med = txtMed.Text;
sd.NetPay = txtNet.Text;
}
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(SaveData));
using (FileStream fs = File.OpenRead("config.xml"))
{
sd = (SaveData)ser.Deserialize(fs);
}
}
}
public struct SaveData
{
public bool Married;
public string PayPd;
public string Allow;
public string Gross;
public string Fit;
public string Soc;
public string Med;
public string NetPay;
}
}

You are loading your object by deserializing.
But Where are you assigning the states back to your controls?
look at frmPayroll_Load function.
You are trying to assign the data back to the object again.
You have to assign data back to form controls.
Should be something like this (you may need to apply data conversions if required):
rdoMarr.Checked = sd.Married;
.
.
.
.
txtFit.Text = sd.Fit;
.
.
.
.

Related

C# Windows Service with multiple timers from file

I have multiple "jobs" with timers in a file.
I want to use all of them but when i start the service i see that only the last timer in the configuration is working
How can i do have multiple timers created based on a List that can change over time (yes i can restart the service when i change the list but i don't want to write a timer foreach
Here is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using InserterService.Dao;
namespace InserterService
{
public partial class InserterService : ServiceBase
{
public InserterService()
{
InitializeComponent();
}
class CustomTimer : System.Timers.Timer
{
public Configurazione configurazione;
}
protected override void OnStart(string[] args)
{
//** CARICA CONFIGURAZIONI **//
// PER OGNI CONFIGURAZIONE DEFINISCO IL TIMER
List<Configurazione> Configurazioni = new List<Configurazione>();
Configurazioni = ModulReader.GetModulCopyDirectory();
int i = 0;
foreach (var item in Configurazioni )
{
i++;
string data = string.Format("CONFIGURAZIONE {0}",i.ToString());
string folder = #"C:\temp\OUT\";
// Filename
string fileName = "Test.txt";
// Fullpath. You can direct hardcode it if you like.
string fullPath = folder + fileName;
File.AppendAllText(fullPath, data);
var timer = new CustomTimer
{
Interval = Int32.Parse(item.TIMER.Trim()),
configurazione = item
};
timer.Elapsed += Lavorazione;
timer.Start();
}
}
public void Lavorazione(object sender, ElapsedEventArgs e)
{
Configurazione configurazione = ((CustomTimer)sender).configurazione;
string data = configurazione.DATA;
string folder = #"C:\temp\OUT\";
// Filename
string fileName = "Test.txt";
// Fullpath. You can direct hardcode it if you like.
string fullPath = folder + fileName;
File.AppendAllText(fullPath, data);
}
protected override void OnStop()
{
}
}
}

Exception Handling in a Windows Forms Application

I'm doing a program for serial communications. To centralize the process of access to serial, created a class.
I am having problem when an exception is lançanda within the class leaves the locked program.
example:
When trying aberir the serial port, can give error and the system is at that point to burst memory.
How should I handle errors?
Put try and catch?
Add another routine?
Error point:
portSerial.Open();
Program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PortSerial.Lib;
namespace ProgramPortSerial
{
public partial class Form1 : Form {
public static LibPortaSerial portSerial = new LibPortSerial();
public Form1()
{
InitializeComponent();
portSerial.LineReceived += new LineReceivedEventHandler(sp1_LineReceived);
portSerial.Init(
ref cmbPortas,
ref cmbVelocidade,
ref cmbBitsDeDados,
ref cmbPariedade,
ref cmbBitsDeParada,
ref cmbControleDeFluxo);
}
void sp1_LineReceived(object sender, LineReceivedEventArgs Args)
{
// Tem que ser em uma nova thread para não travar
Invoke(new Action(() =>
{
memDadosRecebidos.Text += "\r\n" + Args.Resposta;
}));
}
private void btnAbrirPorta_Click(object sender, EventArgs e)
{
portSerial.Open();
}
}
}
Class PortSerial
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace PortSerial.Lib
{
public class LibPortSerial : IDisposable
{
public SerialPort portSerial;
public LibPortSerial()
{
portSerial = new SerialPort();
}
public void Dispose()
{
if (portSerial != null)
portSerial.Dispose();
}
public void Open(
string port,
int veloc,
int bitsData,
string pariedade,
string bitsStop,
string control)
{
portSerial.PortName = port;
portSerial.BaudRate = veloc;
portSerial.DataBits = bitsData;
portSerial.Parity = SetPariedade(pariedade);
portSerial.StopBits = SetBitsStop(bitsStop);
portSerial.Handshake = Setcontrol(control);
portSerial.Open(); // ==> Erro this point
}
}
}
You should write it as:
public void Open(
string port,
int veloc,
int bitsData,
string pariedade,
string bitsStop,
string control)
{
portSerial.PortName = port;
portSerial.BaudRate = veloc;
portSerial.DataBits = bitsData;
portSerial.Parity = SetPariedade(pariedade);
portSerial.StopBits = SetBitsStop(bitsStop);
portSerial.Handshake = Setcontrol(control);
try
{
portSerial.Open(); // ==> Erro this point
}
catch(IOException exp)
{
return exp.Message;
}
}

using variables from another file .cs

I have a project in c# winforms, with a file called: PublicSettings.cs (this file is within a folder called: Class) where I have a variable.
Now, I want to use that variable from another file within the same project.
PublicSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LVSetup.Class
{
class PublicSettings
{
private string _ConnStr = "Connection";
public string ConnStr
{
get
{
return this._ConnStr;
}
set
{
this._ConnStr = value;
}
}
}
}
I want to use the variable ConnStr in the file: frmLogin.cs
frmLogin.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LVSetup.Class;
namespace LVSetup
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
string a = PublicSettings.ConnStr;
}
}
}
But there is no ConnStr within PublicSettings, just (Equals and ReferenceEquals)
What could be wrong here?
You need to make this field static in order to access it without creating a class instance. Or create and instance. What suites the best depends on the logic that you want to apply for this class and how it will be used later.
Instance approach
private void btnEnter_Click(object sender, EventArgs e)
{
var settings = new PublicSettings();
string a = settings.ConnStr;
}
Static field approach
class PublicSettings
{
private static string _ConnStr = "Connection";
public static string ConnStr
{
get
{
return _ConnStr;
}
set
{
_ConnStr = value;
}
}
}
For a connection string, I would either use a Configuration file (app.config) or make the property a static read-only property (since there's often no reason to change a connection string at run-time):
class PublicSettings
{
public static string ConnStr
{
get
{
return "Connection";
}
}
}

how can I add items to my ListView

I keep getting this error and I know why but I need help figuring out how I can solve it. The only way I have been able to add my items it to make a new form but that seems silly.
It wont work if I make all my methods static =(
I keep getting,
"An object reference is required for the non-static field, method, or
property 'Handicap_Calculator.FormMain.listViewLog'
\Form1.cs 74 13 Handicap Calculator"
Here´s my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Handicap_Calculator
{
public partial class FormMain : Form
{
//FormAddScore FormAddNewScore = new FormAddScore();
public static bool addScoreIsShown = false;
public static FormAddScore _FormAddScore;
public static ListViewItem Item;
//public static List<string> ScoreInfo = new List<string>();
public FormMain()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
try
{
if (_FormAddScore == null || _FormAddScore.IsDisposed)
{
_FormAddScore = new FormAddScore();
}
_FormAddScore.Show();
if (_FormAddScore.WindowState == FormWindowState.Minimized)
{
_FormAddScore.WindowState = FormWindowState.Normal;
}
_FormAddScore.BringToFront();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static void AddScore()
{
int Round = 1;
DateTime date = _FormAddScore.date;
string course = _FormAddScore.course;
int holes = _FormAddScore.holes;
int score = _FormAddScore.score;
float courseRating = _FormAddScore.courseRating;
float slopeRating = _FormAddScore.slopeRating;
string[] ScoreInfo = new string[7];
ScoreInfo[0] = Round.ToString();
ScoreInfo[1] = date.ToString();
ScoreInfo[2] = course;
ScoreInfo[3] = holes.ToString();
ScoreInfo[4] = score.ToString();
ScoreInfo[5] = courseRating.ToString();
ScoreInfo[6] = slopeRating.ToString();
AddToList(ScoreInfo);
}
public static void AddToList(string[] ScoreInfo)
{
Item = new ListViewItem(ScoreInfo);
//listViewLog.Items.Add(Item);
}
}
}
Edit...
Here is the class im calling it from:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Handicap_Calculator
{
public partial class FormAddScore : Form
{
public DateTime date;
public string course;
public int holes;
public int score;
public float courseRating;
public float slopeRating;
public FormAddScore()
{
InitializeComponent();
}
private void FormAddScore_FormClosing(object sender, FormClosingEventArgs e)
{
FormMain.addScoreIsShown = false;
}
public void getscore()
{
try
{
date = dateTimePicker1.Value;
course = textBoxCourse.Text;
holes = Convert.ToInt16(textBoxHoles.Text);
score = Convert.ToInt16(textBoxScore.Text);
courseRating = Convert.ToSingle(textBoxCourseRating.Text);
slopeRating = Convert.ToSingle(textBoxSlopeRating.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
getscore();
FormMain.AddScore();
}
}
}
The simple solution is to define your methods AddScore and AddToList as non-static.
public void AddScore()
{
//your code
}
public void AddToList(string[] ScoreInfo)
{
// your code
}
If you want to use static methods you should pass the instance of your Form to the method, on which you want to add items to the ListView.
public static void AddScore(FormMain mainForm)
{
//your code
AddToList(mainForm, ScoreInfo);
}
public static void AddToList(FormMain mainForm, string[] ScoreInfo)
{
// your code
}
Update:
According to your updated code the solution is to pass the instance of your FormMain to your FormAddScore when you create it. In FormAddScore you store the reference to the FormMain instance to call the methods on.
public partial class FormAddScore : Form
{
// your code
private FormMain _mainForm;
public FormAddScore(){
InitializeComponent();
}
public FormAddScore(FormMain mainForm) : this(){
_mainForm = mainForm;
}
In your FormMain when you create the instance of FormAddScore you should use the constructor that expects an instance of FormMain
_FormAddScore = new FormAddScore(this);
With this setup you can change your methods to non-static and you can call the methods of FormMain in your FormAddScore, by using the stored reference in variable _mainForm.
_mainForm.AddScore();

Noob Concern: Assigning a value to variable from new class object. C#

DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
I am creating a new object of the DinnerFun class and trying to assign the value from the numeric up down object from the form to the int variable PeepQty.
When I go into debug mode, I can see that sure enough nudPeepQty has a numeric value, but it is never assigned to PeepQty, and my ending calculation always ends as 0.
As the problem might be something related to something I've done outside this line of code, I will add the rest of my project below:
DinnerParty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MonuEventPlanning
{
class DinnerFun
{
const int FoodCost = 25;
public int PeepQty;
decimal CostOfBeverage;
decimal CostOfDecorations;
decimal TotalCost;
public void CalcDrinks(bool HealthOption)
{
if (HealthOption)
{
CostOfBeverage = 5M;
}
else
{
CostOfBeverage = 20M;
}
}
public void CalcDecorations(bool FancyOption)
{
if (FancyOption)
{
CostOfDecorations = (PeepQty * 15M) + 50M;
}
else
{
CostOfDecorations = (PeepQty * 7.5M) + 30M;
}
}
public decimal CalcTotalCost(bool HealthyOption)
{
if (HealthyOption)
{
TotalCost = (CostOfDecorations + CostOfBeverage) * .95M;
return TotalCost;
}
else
{
TotalCost = (CostOfBeverage + CostOfDecorations) + (PeepQty*25M);
return TotalCost;
}
}
}
}
------------Form1.cs -------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MonuEventPlanning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost();
}
public void DisplayCost()
{
DinnerFun dinnerFun = new DinnerFun();
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}
}
}
The issue is that you are creating another DinnerFun that is not the same as the first one. Naturally the DinnerFun object in DisplayCost will have zero for the property value. Perhaps you meant this...
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost(dinnerFun);
}
public void DisplayCost(DinnerFun dinnerFun)
{
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}

Categories

Resources