Adding to a list box on another form - c#

http://i.stack.imgur.com/DpO5L.jpg
http://i.stack.imgur.com/S9XL4.jpg
how do I take the info from form 1 and add it into form 2?
on form 1 I have many textboxes, a few combo boxes and other stuff, I would like to add these items to a list box on form 2.
this is what I have but its not working
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 ClassofEmployees
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class employee
{ //will include the attributes of all employees of your organization.
//fields for employee
public int employeeId; // 5 digit number to represent employee
public int ssn; //social security number of employee
public string name; //employee name
public int dob; //date of birth
public int pay; //rate of pay
}
class managers : employee
{
public string backgroundCheck;
public string isSalary;
public string responsibilitys;
}
public void getEmployeeData(employee employee)
{
try
{
employee.employeeId = int.Parse(EmployeeID.Text);
employee.ssn = int.Parse(SSN.Text);
employee.name = employeeName.Text;
employee.dob = int.Parse(DOB.Text);
employee.pay = int.Parse(pay.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BCToString()
{
string bcSelectedY;
string bcSelectedN;
if (bcselect.SelectedIndex != 1)
{
bcSelectedY = bcselect.SelectedItem.ToString();
}
else
{
bcSelectedN = bcselect.SelectedItem.ToString();
}
}
public void getMangerData(managers managers)
{
if (bcselect.SelectedIndex != 1)
{
managers.backgroundCheck = "yes";
}
else
{
managers.backgroundCheck = "no";
}
if (salary.SelectedIndex != 1)
{
managers.isSalary = "Yes";
}
else
{
managers.isSalary = "No";
}
managers.responsibilitys = responsibilitys.Text;
}
public void add_Click(object sender, EventArgs e)
{
//create new employee object
employee newemployee = new employee();
//get employee data
getEmployeeData(newemployee);
//create new manager object
managers newmanagerialemployee = new managers();
getMangerData(newmanagerialemployee);
EmployeeCumalitveList.employeeList.Items.Add(employee);
}
private void done_Click(object sender, EventArgs e)
{
EmployeeCumalitveList ecl = new EmployeeCumalitveList
ecl.Show;
this.Hide();
}
}
}
This is where the errors are:
EmployeeCumalitveList.employeeList.Items.Add(employee);
the errors I am getting are:
Error 1 A new expression requires (), [], or {} after
type C:\Users\T-Ali\Desktop\SHawnasschool\vb.net 2
c#\projects\ClassofEmployees\ClassofEmployees\Form1.cs 108 66 ClassofEmployees
Error 2 Inconsistent accessibility: parameter type
'ClassofEmployees.Form1.employee' is less accessible than method
'ClassofEmployees.Form1.getEmployeeData(ClassofEmployees.Form1.employee)' C:\Users\T-Ali\Desktop\SHawnasschool\vb.net
2
c#\projects\ClassofEmployees\ClassofEmployees\Form1.cs 42 21 ClassofEmployees
Error 3 Inconsistent accessibility: parameter type
'ClassofEmployees.Form1.managers' is less accessible than method
'ClassofEmployees.Form1.getMangerData(ClassofEmployees.Form1.managers)' C:\Users\T-Ali\Desktop\SHawnasschool\vb.net
2
c#\projects\ClassofEmployees\ClassofEmployees\Form1.cs 70 21 ClassofEmployees

First of all, did you make the listbox public?
I believe you can do this by selecting the listbox, going to the properties window, finding the Modifiers item, and setting it to Public.
Second, make sure the form that contains the list of employees, is static, and that you're not creating the same form each time you want to add an employee.
Do this by:
namespace WindowsFormsApplication1
{
public static class Program
{
public static EmployeeCumalitveList MyEmployeeList;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MyEmployeeList = new EmployeeCumalitveList();
Application.Run(MyEmployeeList);
}
}
}

Related

Property or indexer must have at least one accessor

I'm learning C#, trying to get to grips with accessors at the moment.
I'm going nuts looking at this, I have no idea what I've done wrong:
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
The Form looks like this:
public partial class BankForm : Form
{
private BankAccount _myAccount;
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
But I get this error:
Property or indexer must have at least one accessor
I'm not getting any errors. Move location of private BankAccount _myAccount;
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 BankForm
{
public partial class BankForm : Form
{
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private BankAccount _myAccount;
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
}
​

Updating a Control Within a Currently Open Form

I am writing a C# Application where I can add various types of students - a normal student, or a academic society student, or a arts and culture society student. On the main form, I have 3 data grids (one lists academic students, one list arts and culture students, and the other lists the normal students). For the user to specify additional information about a student (should they be an academic society student, or an arts and culture student, or both), another form will open up asking the user to add additional Information.
After the information has been specified, I would like to take that information, and add it to the relevant data grid, in other words, update the data grid in the main form.
How I thought I would tackle this idea:
Create a method in the main form to add a new entry to the data grid
Save the main form object into a Form object
Have a method which will will add a new row of data into the form object mentioned in step 2
Update the currently open main form with the form object I had saved.
I tried doing the above, and I get the error:
Error 1 Inconsistent accessibility: parameter type 'ONT2000_Practical_05.AcademicSocieties' is less accessible than method 'ONT2000_Practical_05.Form1.addAcademicStudentRow(ONT2000_Practical_05.AcademicSocieties)' c:\users\okuhle\documents\visual studio 2013\Projects\ONT2000 Practical 05\ONT2000 Practical 05\Form1.cs 35 21 ONT2000 Practical 05
I have 3 classes - AcademicSocieties, ArtsAndCultureSociety and Student...both AcademicSocieties and ArtsAndCultureSociety inherit the Student class. Below is the code for the classes:
THE STUDENT CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class Student
{
private String studentNumber;
private String studentName;
private String studentDegree;
public Student(string number, string name, string degree)
{
studentNumber = number;
studentName = name;
studentDegree = degree;
}
public String getStudentName()
{
return studentName;
}
public String getStudentNumber()
{
return studentNumber;
}
public String getStudentDegree()
{
return studentDegree;
}
}
}
THE ACADEMICSSOCIETY CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
public class AcademicSocieties : Student
{
private String courseCode;
private String societyName;
public AcademicSocieties(String studentName, String studentNumber, String studentDegree, String courseCode, String societyName) : base(studentNumber, studentName, studentDegree)
{
this.courseCode = courseCode;
this.societyName = societyName;
}
public String getCourseCode()
{
return courseCode;
}
public String getSocietyName()
{
return societyName;
}
}
}
THE ARTSANDCULTURE SOCIETY CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ONT2000_Practical_05
{
class ArtsAndCultureSociety : Student
{
private int experienceLevel;
private int competitionWins;
private String societyName;
private Boolean colours;
public ArtsAndCultureSociety(int level, int wins, string societyName, String studentNumber, String studentName, String studentDegree) : base(studentNumber, studentName, studentDegree)
{
experienceLevel = level;
competitionWins = wins;
this.societyName = societyName;
}
}
}
THE MAIN FORM:
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 ONT2000_Practical_05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void academicSocietiesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void degreeLabel_Click(object sender, EventArgs e)
{
}
private void exitApplicationToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
public void addAcademicStudentRow(AcademicSocieties thisStudent) //This is where the Error Occurs
{
academicSocietiesDataGrid.Rows.Add(thisStudent.getStudentName(), thisStudent.getSocietyName(), thisStudent.getCourseCode());
}
private void addStudentButton_Click(object sender, EventArgs e)
{
String studentName = ProgramFunctions.validateTextBoxData(studentNameTextBox);
String studentNumber = ProgramFunctions.validateStudentNumber(studentNumberTextBox);
String studentDegree = ProgramFunctions.validateTextBoxData(degreeTextBox);
if (studentName.Equals(null) || studentNumber.Equals(null) || studentDegree.Equals(null) || studentDegree.Equals("null")) //Error 1 is on this line
{
ProgramFunctions.displayMessage("Data Integrity Error", "As a result of one or more fields failing data validation, this application will not continue processing data");
} else
{
if (artsAndCultureCheckBox.Checked && academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
GeneralStudentSocietyForm generalForm = new GeneralStudentSocietyForm();
generalForm.Visible = true;
generalForm.Focus();
} else if (academicCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
AcademicSocietyForm academics = new AcademicSocietyForm();
academics.Visible = true;
academics.Focus();
} else if (artsAndCultureCheckBox.Checked)
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.setCurrentStudent(newStudent);
ProgramFunctions.saveCurrentForm(this);
ArtsAndCultureForm artsAndCulture = new ArtsAndCultureForm();
artsAndCulture.Visible = true;
artsAndCulture.Focus();
} else
{
Student newStudent = new Student(studentNumber, studentName, studentDegree);
StudentData.addNewStudent(newStudent);
ProgramFunctions.displayMessage("Student Added", "A New Student has successfully been added to the database. Click OK to continue");
studentDataDataGird.Rows.Add(newStudent.getStudentName(), newStudent.getStudentNumber(), newStudent.getStudentDegree());
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
ProgramFunctions.addNewAcademicSociety("Accounting Society");
ProgramFunctions.addNewAcademicSociety("Law Student Society");
ProgramFunctions.addNewAcademicSociety("Science Student Society");
ProgramFunctions.addNewAcademicSociety("Information Technology Student Society");
ProgramFunctions.addNewAcademicSociety("Business Science Student Society");
ProgramFunctions.addNewArtsAndCultureSociety("Choir Society");
ProgramFunctions.addNewArtsAndCultureSociety("Hip Hop Society");
ProgramFunctions.addNewArtsAndCultureSociety("Anime Society");
ProgramFunctions.addNewArtsAndCultureSociety("The Hockey Society");
}
private void studentDataDataGird_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void academicSocietiesDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
THE PROGRAMFUNCTIONS Class (This is where I am saving the Form Object):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ONT2000_Practical_05
{
class ProgramFunctions
{
private static List<String> academicSocieties = new List<String>();
private static List<String> artsAndCultureSocieties = new List<String>();
private static Form1 formObject;
public static void saveCurrentForm(Form1 formData)
{
formObject = formData;
}
public static void academicStudentDataGridRow(AcademicSocieties newStudent)
{
formObject.addAcademicStudentRow(newStudent);
}
public static Form1 updateMainForm()
{
return formObject;
}
public static void addNewAcademicSociety(String societyName)
{
academicSocieties.Add(societyName);
}
public static void addNewArtsAndCultureSociety(String societyName)
{
artsAndCultureSocieties.Add(societyName);
}
public static void displayMessage(String title, String Message)
{
MessageBox.Show(Message, title);
}
public static String validateTextBoxData(TextBox thisTextBox)
{
if (thisTextBox.Text.Equals(null) || thisTextBox.Text.Equals("") || thisTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You may not specify empty data for the student");
return null;
} else
{
thisTextBox.Text = thisTextBox.Text.Trim();
thisTextBox.Text = thisTextBox.Text.ToUpper();
return thisTextBox.Text;
}
}
public static String getSelectedItem(ComboBox thisComboBox)
{
return thisComboBox.SelectedItem.ToString();
}
public static int getArtsAndCultureCount()
{
return artsAndCultureSocieties.Count;
}
public static int getAcademicSocietyCount()
{
return academicSocieties.Count;
}
public static String getAcademicSociety(int index)
{
return academicSocieties[index];
}
public static String getArtsAndCultureSociety(int index)
{
return artsAndCultureSocieties[index];
}
public static String validateStudentNumber(TextBox studentNumberTextBox)
{
if (studentNumberTextBox.Text.Equals(null) || studentNumberTextBox.Text.Equals("") || studentNumberTextBox.Text.Equals(" "))
{
displayMessage("Empty Data Detected!", "You did not input any data...Please be sure you do specify some data");
return null;
} else
{
if (!studentNumberTextBox.Text.StartsWith("s"))
{
displayMessage("Invalid Student Number", "You have entered an invalid student number. Please be sure this student number follows the correct format. The student number must begin with a 's' character. ");
return null;
}
if (studentNumberTextBox.Text.Length != 10)
{
displayMessage("Invalid Student Number", "The student number specified may not be longer than 10 characters");
return null;
}
return studentNumberTextBox.Text;
}
}
}
}
change the access modifier of the class ProgramFunctions,ArtsAndCultureSociety to public.
Could it be you are missing the access modifier 'public' in some of your class definitions? If you don't add public before ArtsAndCultureSociety, it will be private.

Why does a normal class instantiation cause an unhandled overflow exception?

I can't see anything other than an normal class initialized.
Here is the class, class Bet.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab_ADayAtTheRaces
{
public class Bet : Form1
{
public int Bets_Joe;
public int Bets_Bob;
public int Bets_Al;
public int Dog_Joe;
public int Dog_Bob;
public int Dog_Al;
public int Amount;
public int Dog;
public Guy Bettor;
public string GetDescription()
{
Amount = (int)numericUpDownBucksToBet.Value;
Dog = (int)numericUpDownDogToBetOn.Value;
//Bettor =
return Bettor + " placed a bet in the amount of " + Amount + " bucks on dog number " + Dog;
}
public int PayOut(int Winner)
{
return Winner;
}
public void MakeBets()
{
if (joeRadioButton.Checked == true)
{
Bets_Joe = (int)numericUpDownBucksToBet.Value;
Dog_Joe = (int)numericUpDownDogToBetOn.Value;
}
else if (bobRadioButton.Checked == true)
{
Bets_Bob = (int)numericUpDownBucksToBet.Value;
Dog_Bob = (int)numericUpDownDogToBetOn.Value;
}
else if (alRadioButton.Checked == true)
{
Bets_Al = (int)numericUpDownBucksToBet.Value;
Dog_Al = (int)numericUpDownDogToBetOn.Value;
}
}
}
}
Here is the code that throws the exception:
namespace Lab_ADayAtTheRaces
{
public partial class Form1 : Form
{
Bet bets = new Bet(); //**THIS LINE THROWS THE STACKOVERFLOW EXCEPTION**
Greyhound[] dogs = new Greyhound[3];
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
Any help is muchly appriciated... thanks in advance
Kristjan
your Bet inherits from Form1, so Bet() will call to Form1(), and Form1() will again call to Bet() inside it -> again and again -> StackOverflow
Tip: We should never call the constructor of a class in its constructor or its class definition like this:
public class Form1 : Form {
public Form1(){
}
public Form1(string s){
}
public Form1 f = new Form1();//this will throw StackOverflowException
public Form1 f = new Form1("");//this will also throw StackOverflowException
//Form2 inherits from Form1
public Form2 f = new Form2(); //this will throw StackOverflowException
}
//or
public class Form1 : Form {
public Form1(){
Form1 f = new Form1();//This will throw stackoverflowexception
Form1 f = new Form1("");//This won't throw any exception
}
public Form1(string s){
}
}
When a class is initialized, all the members are initialized first before calling the constructor, hence the line Bet bets = new Bet(); is executed before initializing your Form1. So you have to avoid it. To initialize new Bet(), you should call it in some event so that the event will never be fired by calling the constructor, such as Load.
Bet bets;//Just declare it without initializing it
private void Form1_Load(object sender, EventArgs e){
bets = new Bet();
}

Can I pass a List of objects from one Form to another in C#?

I have setup an Class that holds names/Numbers/ect, and created a List of objects to hold them. I want to display them on a second Form in a ListView. Right now I am using a getter like...
public List<Employee> GetEmpList(){
return EmployeeList;
}
Then in the second Form's constructor I am using the Form1.GetEmpList() like...
DisplayForm{
InitializeComponent();
LoadEmployees(EmployeeAddition.GetList());
}
I am getting and error saying "an object reference is required for the nonstatic field". The method I am calling is non-static, and returns a reference to the List in the Form1 class. I have even tried to just make the List public and calling using Form1.List but it still gives me the same error.
Is there a way to pass a List between Form classes or is it impossible?
EDIT: Poeple said that more information was needed. I didn't want to copy paste all the code here, but I am going to put a good chunk just because I am new and not quite sure what is relevant and what is not. (I am taking a class, but remotely, and my teacher is...well a remote teacher, useless. She actually told me to ask here)
I guess I am missing how to instatize a method, I thought that when the object was created from the class the method became part of the object. The Method is part for the Form1 (Renamed but thats what it is) class/object. I will dumb the code under here, I don't know if that is frowned upon; if so I am sorry.
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 EmplyeeList
{
public partial class EmployeeDisplay : Form
{
public EmployeeDisplay()
{
InitializeComponent();
LoadEmployees(EmployeeAddition.GetList());
}
private void LoadEmployees(IList<CorpEmployee> emp)
{
foreach (CorpEmployee ce in emp)
{
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add(ce.Name);
lvi.SubItems.Add(ce.Address);
lvi.SubItems.Add(ce.PhoneNumber);
lvi.SubItems.Add(ce.ServiceArea);
lvi.SubItems.Add(ce.EmplNumber.ToString());
lvi.SubItems.Add(ce.RoomNumber.ToString());
lvi.SubItems.Add(ce.PhoneExt.ToString());
lvi.SubItems.Add(ce.email);
displayListView.Items.Add(lvi);
}
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
This is the first Form class to load...
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 EmplyeeList
{
public class EmployeeAddition : Form
{
//Create a list to hold CorpEmployee objects.
private List<CorpEmployee> CorpEmplList = new List<CorpEmployee>();
public EmployeeAddition()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
int testingNum; //Used for output in parsing numbers
//If statments are used to make sure ints are ints, and nothing is blank.
if (Int32.TryParse(employeeNumTextBox.Text, out testingNum) || ! (employeeNumTextBox.Text == ""))
{
if (Int32.TryParse(roomNumTextBox.Text, out testingNum) || !(roomNumTextBox.Text == ""))
{
if (Int32.TryParse(phoneExtTextBox.Text, out testingNum) || !(phoneExtTextBox.Text == ""))
{
if (!(nameTextBox.Text == "") || !(addressTextBox.Text == "") || !(titleTextBox.Text == "") || !(phoneNumberTextBox.Text == "") ||
!(serviceAreaTextBox.Text == "") || !(emailTextBox.Text == ""))
{
//If all fields are filled in right then we add the object to the List
CorpEmplList.Add(CreateCorpEmployee(nameTextBox.Text, addressTextBox.Text, titleTextBox.Text,
phoneNumberTextBox.Text, serviceAreaTextBox.Text,
Convert.ToInt32(employeeNumTextBox.Text), Convert.ToInt32(roomNumTextBox.Text),
Convert.ToInt32(phoneExtTextBox.Text), emailTextBox.Text));
//Let the user know it was added
MessageBox.Show("Employee was added!");
//Clear fields
ClearAllFields();
}
else
{
MessageBox.Show("All fields must be filled in.");
}
}
else
{
MessageBox.Show("Phone Ext.# should be a number");
}
}
else
{
MessageBox.Show("Check your Room# and try again.");
}
}
else
{
MessageBox.Show("Employee Number Should be a number.");
}
}
//This takes in all the employee fields and returns a contructed object
private CorpEmployee CreateCorpEmployee(String name, String address, String title, String phoneNumber,
String serviceArea, int emplNumber, int roomNumber, int phoneExt, String email)
{
CorpEmployee corpEmpObject = new CorpEmployee(name, address, title, phoneNumber, serviceArea, emplNumber, roomNumber, phoneExt, email);
return corpEmpObject;
}
//This just clears all the fiels
private void ClearAllFields()
{
nameTextBox.Text = "";
addressTextBox.Text = "";
titleTextBox.Text = "";
phoneNumberTextBox.Text = "";
serviceAreaTextBox.Text = "";
employeeNumTextBox.Text = "";
roomNumTextBox.Text = "";
phoneExtTextBox.Text = "";
emailTextBox.Text = "";
}
//This returns the List of CorpEmployees
public List<CorpEmployee> GetList()
{
return CorpEmplList;
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearButton_Click(object sender, EventArgs e)
{
ClearAllFields();
}
private void showButton_Click(object sender, EventArgs e)
{
EmployeeDisplay ed = new EmployeeDisplay();
ed.Show();
}
}
}
After relooking at the code I think I might see what you are saying about calling it from a static class, not an object. Is there a way to find the name of the Object that the Compiler creates from the first Form?
The first problem you are having is you are treating the GetEmpList() function as an static method. It is not static and probably shouldn't be static. That is why people are saying you need to create an instance of it. However, looking at what you are asking the way you are going about this is probably flawed in a more fundamental way that just creating a new version of the form will solve. The problem is you want to pass model data between forms. Without more information it is really hard to tell how you want this all to go together. However you probably already have an instance of the EmployeeAddition form and don't need to create another instance inside the constructor of your DisplayForm. Instead what you should do is make the LoadEmployees method public and pass the results of GetEmpList() into that.
So your structure would be more like
public class EmployeeAddition : Form {
...
public List<Employee> GetEmpList(){
return EmployeeList;
}
...
public void ShowDisplayForm(){
var displayForm = new DisplayForm();
displayForm.LoadEmployees(GetEmpList());
displayForm.Show();
}
...
}
Of course this structure may be slightly off as I'm guessing at which form will own which form but this is closer to what you want.
try use "new"
DisplayForm{
InitializeComponent();
EmployeeAddition = new EmployeeAdditionClass();
LoadEmployees(EmployeeAddition.GetList());
}

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

Categories

Resources