Executing or closing program based on file contents - c#

So my program is a simple form that a user has to read, agree to the terms, and close the window. When the user closes the window it takes their login name and date / time, writes it to a txt file and exits. When the program loads, I want it to check the file for the existing username. If it finds the username, check the date on which it was recorded and if it was within 6 months exit the program. If it was recorded more than 6 months ago, run the program. Obviously, if the reading of the file doesn't find the username I want the program to run as well. Here is my code so far -
namespace EUSAA
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
if (chkAgree.Checked)
{
btnClose.Visible = true;
}
else btnClose.Visible = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
using (StreamWriter sw = File.AppendText(#"I:\Security Awareness Signed Users\Signed Users.txt"))
{
sw.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name + "\t" + DateTime.Now.ToString());
}
Environment.Exit(0);
}

This isn't a code writing site; but I was feeling generous. The following class encapsulates storing and retrieving the latest agreement for the current user.
public class AgreementRepository
{
private const string FileLocation = #"I:\Security Awareness Signed Users\Signed Users.txt";
private const char Separator = '\t';
public void AppendAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
using (StreamWriter sw = File.AppendText(FileLocation))
{
sw.WriteLine($"{currentUser}{Separator}{DateTime.Now:O}");
}
}
public DateTime? GetLastAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
if (File.Exists(FileLocation) == false)
{
return null;
}
var lastAgreement = File.ReadLines(FileLocation)
.Select(x => x.Split(Separator))
.Where(x => x.Length == 2 && string.Equals(x[0], currentUser, StringComparison.CurrentCultureIgnoreCase))
.Select(x => GetDateTime(x[1]))
.Max();
return lastAgreement;
}
private static DateTime? GetDateTime(string input)
{
DateTime result;
if (DateTime.TryParse(input, out result))
{
return result;
}
return null;
}
private static string GetCurrentUser()
{
return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
To use this, your form would become...
public partial class frmMain : Form
{
private readonly AgreementRepository _agreementRepository;
public frmMain()
{
_agreementRepository = new AgreementRepository();
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
var lastAgreement = _agreementRepository.GetLastAgreementForCurrentUser();
// NOTE: The following condition deals with the fact that lastAgreement could be null
if (lastAgreement > DateTime.Now.AddMonths(-6))
{
Close(); // or Environment.Exit; depends what you need
}
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
btnClose.Visible = chkAgree.Checked; // simplification of your posted code
}
private void btnClose_Click(object sender, EventArgs e)
{
_agreementRepository.AppendAgreementForCurrentUser();
Environment.Exit(0); // Would 'Close()' be enough?
}
Hope this helps

Related

Passing values from form1 to form2 via button click to form2 [duplicate]

This question already has an answer here:
How to open new form, pass parameter and return parameter back
(1 answer)
Closed 4 years ago.
frmPlaceOrder is my form1. I need to pass the firstName, lastname and Address from this form to the second one which will do the other functions. I don't know how to do that.
namespace Lab1_OrderCake
{
public partial class frmPlaceOrder : Form
{
public static CustomerInformation customer;
public static Address address;
public frmPlaceOrder()
{
InitializeComponent();
customer = new CustomerInformation(txtFName.Text, txtLName.Text);
address = new Address(txtAddress.Text, txtCity.Text, txtPC.Text, txtProvince.Text);
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
if (txtFName.Text == "")
{
MessageBox.Show("Please enter first name", "Data Missing");
txtFName.Focus();
return;
}
if (txtLName.Text == "")
{
MessageBox.Show("Please enter Last name", "Data Missing");
txtLName.Focus();
return;
}
else
{
frmCakeOrder newCust = new frmCakeOrder();
this.Hide();
newCust.ShowDialog();
this.Close();
}
}
}
}
The second form; after the first one has been filled out needs to take the values from form1 and display it with the other values(frmCakeOrder values) in the second form. It needs to be seen in the View and Order events when i click it.
here is the Second form:
namespace Lab1_OrderCake
{
public partial class frmCakeOrder : Form
{
Order cakeOrder;
public List<Cake> cakeList;
public frmCakeOrder()
{
InitializeComponent();
cmbTraditionalCake.SelectedIndex = 0;
cakeOrder = new Order();
gbCustomCake.Visible = false;
this.Size = new Size(700,360);
cakeList = new List<Cake>();
}
private void bttnOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Confirm Order", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlgMsg == DialogResult.Yes)
{
MessageBox.Show(cakeOrder.PrintConfirmation());
}
else
{
MessageBox.Show ("The order has not been placed");
}
bttnReset.Focus();
cakeOrder.ClearCart();
}
private void radCustom_CheckedChanged(object sender, EventArgs e)
{
if (radCustom.Checked)
{
cmbTraditionalCake.Enabled = false;
gbCustomCake.Visible = true;
}
else
{
cmbTraditionalCake.Enabled = true;
gbCustomCake.Visible = false;
}
}
private void btnView_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
cakeOrder.NumOfCakes=1;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Your order: ", MessageBoxButtons.YesNo , MessageBoxIcon.Information);
if (dlgMsg == DialogResult.No)
{
cakeOrder.ClearCart();
MessageBox.Show("Please enter and confirm your order!");
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (radCustom.Checked)
{
string flavour, occasion;
flavour = occasion = "";
int layers;
//for flavor
if (radBanana.Checked)
flavour = "Banana";
else if (radChocolate.Checked)
flavour = "Chocolate";
else if (radVanilla.Checked)
flavour = "Vanilla";
if (radTier2.Checked)
layers = 2;
else if (radTier3.Checked)
layers = 3;
else
layers = 1;
if (radGraduation.Checked)
occasion = radGraduation.Text.TrimStart(new char[] { '&' });
else if (radWedding.Checked)
occasion = radWedding.Text.TrimStart(new char[] { '&' });
else occasion = radAnniversary.Text.TrimStart(new char[] { '&' });
cakeOrder.AddCake(new Custom(flavour, occasion, layers));
}
else
{
cakeOrder.AddCake(new Traditional(cmbTraditionalCake.SelectedItem.ToString()));
}
cakeList.Add(cakeOrder);
}
}
}
There are many ways to do this. Try it this way.
private void btnPlaceOrder_Click(object sender, EventArgs e) {
string fname = textBox1.Text;
frmCakeOrder frm = new frmCakeOrder(textBox1.Text);
frm.Show();
}
And in frmCakeOrder,
public frmCakeOrder(string fname) {
InitializeComponent();
textBox1.Text = fname;
}
You can pass the data in the constructor:
public class Form1: from{
//constructor
public void Form1(){
}
public void button_click(){
//Get the data
var firstName = textFirstName.text;
var secondName= textSecondName.text;
var address= textAddress.text;
//Pass the data on the constructor of Form2
Form2 f2 = new Form2(firstName,secondName, address);
f2.show();
}
}
public class Form2: Form{
//constructor with data or parameters
public void Form2(string firstName, string lastName, string Address){
//do dosomething with the data
txtFirstName.text = firstName;
}
}
*sorry if it has sintaxys errors.... but thats the idea.

C# - Windows Application - Saving List

I have made a simple TO-DOs program that gets input from a text box then place it in another text box. With tick boxes next to it,
this is all fine except i Cannot save the list eg. the item and if it's finished or not.
Please could anyone help me be able to save this list of items.
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 TO_DOs
{
public partial class Form1 : Form
{
private bool text1, text2, text3, text4, text5, text6, text7, text8;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (text1 == false)
{
textBox2.Text = textBox1.Text;
}
else if (text2 == false)
{
textBox3.Text = textBox1.Text;
}
else if (text3 == false)
{
textBox4.Text = textBox1.Text;
}
else if (text4 == false)
{
textBox5.Text = textBox1.Text;
}
else if (text5 == false)
{
textBox6.Text = textBox1.Text;
}
else if (text6 == false)
{
textBox7.Text = textBox1.Text;
}
else if (text7 == false)
{
textBox8.Text = textBox1.Text;
}
else if (text8 == false)
{
textBox9.Text = textBox1.Text;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
text1 = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
text2 = true;
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
text4 = true;
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
text5 = true;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
text6 = true;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
text7 = true;
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
text8 = true;
}
}
}
I would do it like this:
Create a class to store your values in:
public class ListEntry
{
public string Text { get; set; }
public bool Finished { get; set; }
}
Then I would create 2 Methods:
public List<ListEntry> UI_To_List(); //Create UI from your saved file
public void List_To_UI(List<ListEntry> entries); //Process your UI
Now it's your choice on how to store your list.
You could store it as JSON or XML.
A few recommendations:
I would create a UserControl for your TextBox + CheckBox
Display the 'List of UserControls' in a FlowLayoutPanel
=> then you can process the FlowLayoutPanel.Controls List.
This will make your List dynamically size to an 'unlimited' amount of items.
Short example:
Create a UserControl (Rightclick project for that):
Add these 2 methods to the code of your UserControl (F7 / rightclick => View Code):
public void SetText(string text)
{
//Set the Text of your TextBox in the UserControl:
textBox1.Text = text;
}
public void SetFinished(bool finished)
{
//Set the Checked of your CheckBox in the UserControl:
checkBox1.Checked = finished;
}
In your MainForm add an FlowLayoutPanel (from ToolBox).
Add your Data like this (using class from above):
/// <summary>
///
/// </summary>
/// <param name="entries">You will get them from loading your previously saved file</param>
public void CreateUI(List<ListEntry> entries)
{
foreach (ListEntry entry in entries)
{
//Create new instance of your UserControl
TaskView view = new TaskView();
view.SetFinished(entry.IsFinished);
view.SetText(entry.Text);
//Add that to your UI:
this.flowLayoutPanel1.Controls.Add(view);
}
}
The result will look like this:
I'm not sure what exactly it is that you want to save in a list... but here's just a tip when checking conditions, instead of using if (text1 == false), simply do if (!text1) as this means "is not true" because by default if (text1) will return true.
private void button1_Click(object sender, EventArgs e)
{
if (!text1)
{
textBox2.Text = textBox1.Text;
}
else if (!text2)
{
textBox3.Text = textBox1.Text;
}
// Left out the rest of the else ifs
}
You are casting textboxes wrong. For example when you change textBox4, you gave text3 true.
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
Then you cast
TextBox4.Text = TextBox1.Text;
It changes TextBox4.Text to TextBox1.Text.
You probably want to save TextBox4.Text here at TextBox1.Text so you sould change all if blocks like that. So you have to give only one "true" function for changed textBox sign and change if blocks
if(text(boolNum))
TextBox1.Text = TextBox(Number).Text;
Just swap them and try like that.
If you want to save another thing by another way. You have to be more spesific.
You can use a CheckedListbox to hold all tot actions.
You can then tick the itemsand for instance in the OK button you include a save action:
foreach(var item in MyCheckedListbox.CheckedItems)
{
Console,WriteLine(item.Text);
}
Lets see the answer from Felix D. He tells you exactly how to create a class and save the items into it. But now you only have a List that will be available as long as your software is running. You still need to save it somewhere on your desktop.
Lucky for you, you got a really simple pattern.
string; boolean
So how about you make it yourself simple? Just create a textfile and write your entries, as example in a csv marked with a ; for every information?
Example:
class Program
{
public class tmpClass
{
public string Text;
public bool tick;
}
public List<tmpClass> tmpList = new List<tmpClass>();
static void Main(string[] args)
{
//Stuff
}
public void WriteToFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamWriter tmpWriter = new StreamWriter(tmpTextFilePath))
{
string tmpTextToWrite = String.Empty;
for (int i = 0; i < tmpList.Count; i++)
{
tmpClass tmpEntry = tmpList[i];
tmpTextToWrite += tmpEntry.Text + ";" + tmpEntry.tick;
}
tmpWriter.WriteLine(tmpTextToWrite);
}
//Now we wrote a text file to you desktop with all Informations
}
public void ReadFromFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamReader tmpReader = new StreamReader(tmpTextFilePath))
{
string tmpText = tmpReader.ReadLine();
string tmpInput = String.Empty;
tmpClass tmpClass = new tmpClass();
int i = 0;
foreach (char item in tmpText)
{
if(item.Equals(";".ToCharArray()))
{
if (i == 0)
{
tmpClass.Text = tmpInput;
i = 1;
tmpInput = String.Empty;
}
else
{
if (tmpInput == "True")
tmpClass.tick = true;
else
tmpClass.tick = false;
i = 0;
tmpInput = String.Empty;
tmpList.Add(tmpClass);
}
}
tmpInput += item;
}
}
}
}
This should simply write a txt File to your desktop with your information and read one and save it to your list.

Pass HTML id in another web form

I try to display crystal report in Report.aspx. so for this first i create class "``report_class` and in that class i create function like this:
using cookies
in webform2 i try this
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue, ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page, string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
then on button click
protected void Button6_Click(object sender, EventArgs e)
{
try
{
string datef = string.Empty;
setCookiesValue(this, "fromdate", "todate","regiondrop", ref ret);
report_class r = new report_class();
Report_Detail report = new Report_Detail();
Response.Redirect("Reports.aspx");
}
catch
{
Label4.Visible = true;
}
}
and in reports.aspx
protected void Page_Load(object sender, EventArgs e)
{
Report_Detail report = new Report_Detail();
report_class r = new report_class();
string date_f = getCookies(this, "fromdate");
string date_t = getCookies(this, "todate");
string drop_r = getCookies(this, "regiondrop");
r.Bindreport_class(report, Convert.ToDateTime(date_f),
Convert.ToDateTime(date_t), Convert.ToString(drop_r));
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.DataBind();
}
but this show error
Error 8 No overload for method 'setCookiesValue' takes 5 arguments
Error 3 The name 'getCookies' does not exist in the current context
You just need to pass the value from for Example form1 to form2:
Do it this way:
FORM2
public partial class Form2 : Form
{
public static Label lblvar= null;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
FORM1:
public partial class Form1 : Form
{
public Form1()
{
Form2.lblvar = lblvarinform1;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lblvarinform1.Text = txtdatepicker.Text;
Form2.lblvar.Text = lblvarinform1.Text;
}
}
USING COOKIES:
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue,ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page,string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
using the function above:
set cookies new value:
string ret = string.Empty;
setCookiesValue(this,"yourcookiesname","thisisyourdatevaue_or_any",ref ret);
get cookies value in another form:
string getval = getCookies(this,"yourcookiesname");

Enable button C#

I have an user control calling a method on my main form and this method should enable a button (by default this button is disabled) on the same form, but it's not working.
private void button1_Click(object sender, EventArgs e)
{
Form1 fr = new Form1();
fr.login(textBox1.Text, textBox2.Text);
}
And here is my method
public void login(string username, string password)
{
Connect();
sendMessage("LoginAction,Username=" + username + "UserPassword=" + password);
}
Here is where the button is enabled
private void commandInterpreter(string Message)
{
if(Message.Contains("LoginSuccess,") == true)
{
name = Message.Remove(Message.IndexOf("LoginSuccess,Name="), 18);
Bt2En = true;
}
}
Here is where I'm exposing my button properties:
public bool Bt2En
{
get { return button2.Enabled; }
set { button2.Enabled = value; }
}
I solved my problem doing this, these are my methods from Form1:
public void login()
{
Connect();
Login lg = this.lg;
string username = lg.Username;
string password = lg.Password;
MessageBox.Show(username + "\n" + password);
}
private void button1_Click(object sender, EventArgs e)
{
login();
}
And this one is from my user control:
public string Username
{
get { return textBox1.Text; }
}
public string Password
{
get { return textBox2.Text; }
}
Thanks Steve and Bradley Uffner for help and everyone who tried. I'm posting the answer for who has the same problem.
Bt2En is a property but You use such as methods.
public void bt2En(bool flag)
{
if(flag)
button.Enable=true;
}

How to use class type array in different forms in c#

I am beginner to c#. I am stuck on this assignment. I am trying to store values in class type global array but array is not saving this. I have tried a lot but failed.
Here is the code:
public class GlobalVariable
{
public static Employeeclass[] staff = new Employeeclass[10];
public static int total=0;
}
public class Employeeclass
{
public int id;
public string name;
public double salary;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var myform = new Form2();
myform.Show();
}
private void button2_Click(object sender, EventArgs e)
{
var myForm = new Form3();
myForm.Show();
}
private void button3_Click(object sender, EventArgs e)
{
double totalsalary = 0;
for (int i = 0; i < GlobalVariable.total; i++)
{
totalsalary+=GlobalVariable.staff[i].salary;
}
string a = GlobalVariable.total.ToString();
string b = totalsalary.ToString();
MessageBox.Show("total employee = " + a +"\ntotal salary = " + b);
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
public void button1_Click(object sender, EventArgs e)
{
if (textBox2 == null)
{
MessageBox.Show("please enter employee name");
}
else
{
GlobalVariable.staff[GlobalVariable.total].id = Convert.ToInt32(textBox1.Text);
GlobalVariable.staff[GlobalVariable.total].name = textBox2.Text;
GlobalVariable.staff[GlobalVariable.total].salary = 0.0;
GlobalVariable.total++;
}
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = (GlobalVariable.total + 1).ToString();
}
}
public partial class Form3 : Form
{
//string temp;
//double a;
public Form3()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Clear();
for (int i = 0; i < GlobalVariable.total; i++)
{
comboBox1.Items.Insert(i,GlobalVariable.name[i]);
// comboBox1.Items.Add(GlobalVariable.name[i]);
}
if (comboBox1.SelectedItem != null)
{
textBox1.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
var myform = new Form2();
myform.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
textBox1.Enabled = true;
}
}
}
Your code doesn't initialize the employees. You have to create a new instance of the employee first (unlike with structs, where the default is already a fully working "instance"):
public void button1_Click(object sender, EventArgs e)
{
if (textBox2 == null)
{
MessageBox.Show("please enter employee name");
}
else
{
// Create a new instance in the array
GlobalVariable.staff[GlobalVariable.total] = new Employeeclass();
GlobalVariable.staff[GlobalVariable.total].id =
Convert.ToInt32(textBox1.Text);
GlobalVariable.staff[GlobalVariable.total].name = textBox2.Text;
GlobalVariable.staff[GlobalVariable.total].salary = 0.0;
GlobalVariable.total++;
}
this.Close();
}
However, I have to point out this is a very unhappy design. Global variables? Fixed-length arrays for variable-length data? Non-existent encapsulation?
For example, a better way might be to create the dialogs as, well, dialogs:
private NewEmployeeForm()
{
InitializeComponent();
}
public static EmployeeClass ShowDialog()
{
var frm = new NewEmployeeForm();
while (frm.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(frm.tbxName.Text))
{
MessageBox.Show("Please, enter the employee name.");
}
else
{
var emp = new EmployeeClass();
emp.Id = int.Parse(frm.tbxId.Text);
emp.Name = frm.tbxName.Text);
return emp;
}
}
return null;
}
Forget coding like it's 1980. It's really necessary to separate your code into more or less isolated parts. Read up a bit on object oriented programming, especially encapsulation. Use meaningful names for your variables and controls, even in your learning projects! You really need the habit, it's non-negotiable.
Also, try to look for a way that solves your problem first. For example, there's a List class in .NET, that handles a self-expanding list of data. So you can use something like this:
List<EmployeeClass> employees = new List<EmployeeClass>();
employees.Add(emp1);
employees.Add(emp2);
employees.Add(emp3);
MessageBox.Show("I've got " + employees.Count + " employees!");
Don't forget error handling. I know you're just making a learning project, but again, you want the right habits. Parsing a string to an integer? Check that it's actually an integer first. Handle the possible exception. Use data validation. If I enter hi in your textBox1, your application is going to crash or show an "break / continue / abort" dialogue. That's not good.
You need to initialize each of the "EmployeeClass" Objects in your array.
By default, when the array is created it has 10 slots filled with "null"
I recommend adding a static constructor:
public static class GlobalVariable
{
public static Employeeclass[] staff;
public static int total=0;
static GlobalVariable()
{
staff = new Employeeclass[10];
for (int i = 0; i < staff.Length; i++)
staff[i] = new EmployeeClass();
}
}
The static constructor is called when you first reference anything in the GlobalVariable class. Also the class should be declared "static" because all of its members are static. The compiler can make more efficient code in this way.
Cheers and good luck learning C#
for (int i = 0; i < GlobalVariable.total; i++)
GlobalVariable.total is 0, so this loop will never be run through. Either set total to 10, or change to:
for (int i = 0; i < GlobalVariable.staff.Count; i++)
Also, there's no actual elements in the staff array, so it wouldn't work anyway.

Categories

Resources