Updating a Control Within a Currently Open Form - c#

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.

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

Type used as a variable error

I am making an application to store tickets for boarding a place for a imaginary airline.
I have created a Ticket class see below
public class ticket
{
String lastName;
String firstName;
String origin;
String destination;
String flightNumber;
String seatNumber;
String date;
public ticket()
{
}
public ticket(String lastname, String firstName, String origin, String destination,
String flightNumber, String seatNumber, String date)
{
}
I have two ticket classes, first and economy. The plane can only hold 10 seats. So my structure is having two arrays of ticket objects, one containing 4 ticket objects "first class" and one containing 6 ticket objects "economy class". See below
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
I have to assign the seats randomly within their respective ticket arrays. I am calling my get method (example below) to check for duplicates, that is, that the randomly assigned seat is already filled or not.
public String getLastName()
{
return this.lastName;
}
When I run my program I get the Error WindowsFormsApplication1.ticket' is a 'type' but is used like a 'variable' (relevant code below)
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticket[rand].getLastName = null)
{
ticket[rand].setLastName = txbLastName.Text;
ticket[rand].setFirstName = txbFirstName.Text;
ticket[rand].setOrigin = txbOrigin.Text;
ticket[rand].setDestination = txbDestination.Text;
ticket[rand].setFlightNumber = txbFlightNumber.Text;
ticket[rand].setSeatNumber = txbSeatNumber.Text;
ticket[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
What my intention was is to assign the new ticket object a random seat (position) in the array, and most of my experience is with java. I think this is a syntax error from me using java-like syntax. Any pointers to get this to work properly?
Full Program Below
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
}
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticket[rand].getLastName = null)
{
ticket[rand].setLastName = txbLastName.Text;
ticket[rand].setFirstName = txbFirstName.Text;
ticket[rand].setOrigin = txbOrigin.Text;
ticket[rand].setDestination = txbDestination.Text;
ticket[rand].setFlightNumber = txbFlightNumber.Text;
ticket[rand].setSeatNumber = txbSeatNumber.Text;
ticket[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
}
public class ticket
{
String lastName;
String firstName;
String origin;
String destination;
String flightNumber;
String seatNumber;
String date;
public ticket()
{
}
public ticket(String lastname, String firstName, String origin, String destination,
String flightNumber, String seatNumber, String date)
{
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return this.lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return this.firstName;
}
public void setOrigin(String origin)
{
this.origin = origin;
}
public String getOrigin()
{
return this.origin;
}
public void setDestination(String destination)
{
this.destination = destination;
}
public String getDestination()
{
return this.destination;
}
public void setFlightNumber(String flightNumber)
{
this.flightNumber = flightNumber;
}
public String getFlightNumber()
{
return this.flightNumber;
}
public void setSeatNumber(String seatNumber)
{
this.seatNumber = seatNumber;
}
public String getSeatNumber()
{
return this.seatNumber;
}
public void setDate(String date)
{
this.date = date;
}
public String getDate()
{
return this.date;
}
}
}
Your ticket[rand] needs to be either ticketFirst[rand] or ticketEcon[rand]. They also need to be defined outside of the Form1 constructor to be able to access them elsewhere in the form.
e.g.
public partial class Form1 : Form
{
ticket[] ticketFirst = new ticket[4];
ticket[] ticketEcon = new ticket[6];
public Form1()
{
InitializeComponent();
ticketFirst = new ticket[4];
ticketEcon = new ticket[6];
}
private void btnSubmit_Click(object sender, EventArgs e)
{
Random random = new Random();
int rand = random.Next(0, 4);
if (ticketFirst[rand].getLastName = null)
{
ticketFirst[rand].setLastName = txbLastName.Text;
ticketFirst[rand].setFirstName = txbFirstName.Text;
ticketFirst[rand].setOrigin = txbOrigin.Text;
ticketFirst[rand].setDestination = txbDestination.Text;
ticketFirst[rand].setFlightNumber = txbFlightNumber.Text;
ticketFirst[rand].setSeatNumber = txbSeatNumber.Text;
ticketFirst[rand].setDate = txbDate.Text;
}
else
{
MessageBox.Show("Seat Assignment Failed, try again.", "Seat Assignment");
}
}
}
Your ticket arrays only exist in the form constructor. In order to use it in events, methods... you must create a field on the class...
public partial class Form1 : Form
{
private Ticket[] tickets = new Ticket[5];
...
}
In C# you should:
Use Properties rather than methods for gets and sets.
Use TitleCase for class names (instead of ticket, name as Ticket)
In .NET, the convention is to give types TitleCase names, but your class ticket is lowercased, which causes the compiler to be confused between a variable named ticket and your class, also named ticket.
Change the name of the class to the title-cased Ticket and it will work.

Adding to a list box on another form

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

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

how to declare global function or method using c#?

Can anyone tell me how to declare a global function in c#, similar to what a Module does in VB.net?
I need to call a function that can be called in my form1, form2, and form3.
i have this code :
using System.Data.OleDb;
namespace XYZ
{
public static class Module
{
public static void dbConnection()
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb";
con.Open();
}
}
}
and form1:
using System.Data.OleDb;
using XYZ;
namespace XYZ
{
public partial class frmReports : Form
{
public frm1()
{
InitializeComponent();
}
private void frm1_Load(object sender, EventArgs e)
{
Module.dbConnection();
OleDbCommand cm = new OleDbCommand("SELECT * FROM table", con);
}
}
}
but i has an error: "The name 'con' does not exist in the current context".
If you're using C# 6.0 or later, you could use using static.
For example,
using static ConsoleApplication.Developer;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
// Global static function, static shorthand really
DeveloperIsBorn(firstName: "Foo", lastname: "Bar")
.MakesAwesomeApp()
.Retires();
}
}
}
namespace ConsoleApplication
{
class Developer
{
public static Developer DeveloperIsBorn(string firstName, string lastname)
{
return new Developer();
}
public Developer MakesAwesomeApp()
{
return this;
}
public Developer InsertsRecordsIntoDatabaseForLiving()
{
return this;
}
public void Retires()
{
// Not really
}
}
}
One more example:
using static System.Console;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
WriteLine("test");
}
}
}
You could create a static class.
namespace MyNamespace
{
public static class MyGlobalClass
{
public static void MyMethod() { ... }
}
}
You would then add the namespace in the using section of your calling class to access it. Like this:
using MyNamespace;
public class CallingClass
{
public void CallingMethod()
{
MyGlobalClass.MyMethod();
}
}
You can create a static class (even enclose it in it's own namespace so as not to pollute the main project namespace), then call it from anywhere:
namespace SomeNamespace
{
public static class SomeClass
{
public static string SomeMethod()
{
...
}
}
}
Then, in your code, you can call it using:
string x = SomeNamespace.SomeClass.SomeMethod();
Or, you can set up a using at the top of the code and just reference it without the namespace:
using SomeNamespace;
...
string x = SomeClass.SomeMethod();
#kol is right, there are NO global functions in C#. Take a look at this post MSDN post. I would use layers (I renamed your "Module" class to "TransactionsModule") and It would look like this:
using System;
using System.Collections.Generic;
using System.Data.OleDb;
namespace XYZ
{
public class TransactionsModule
{
public List<Person> GetPersons(string query, string connectionString)
{
List<Person> dbItems = new List<Person>();
OleDbConnection conn = new OleDbConnection(connectionString);
try
{
conn.Open();
var cmd = new OleDbCommand(query, conn);
cmd.CommandText = query;
using (OleDbDataReader reader = cmd.ExecuteReader())
{
Person objPerson = new Person();
//These are the columns returned
objPerson.Name = Convert.ToString(myReader["Name"]);
objPerson.Age = Convert.ToInt32(myReader["Age"]);
dbItems.Add(objPerson);
}
}
catch(OleDbException ex)
{
throw ex;
}
finally
{
conn.Close();
}
return dbItems;
}
}
//This class should be in another Layer, but I placed it here since It's a quick Example
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
All the logic was abstracted to the TransactionsModule class, then you only need to call the Method: GetPersons. Take a look:
using System;
using System.Collections.Generic;
using XYZ.TransactionsModule;
namespace XYZ
{
public partial class frmReports : Form
{
public frm1()
{
InitializeComponent();
protected TransactionsModule moduleTran;
}
private void frm1_Load(object sender, EventArgs e)
{
//We initialize the Data Access Layer class
moduleTran = new TransactionsModule();
//This ConnectionString should be in your app.config
string conString = "provider= microsoft.jet.oledb.4.0;data source=..\\dbCooperative.mdb";
string sqlQuery = "SELECT * FROM table";
List<Person> ItStaff = moduleTran.GetPersons(sqlQuery, conString);
}
}
}

Categories

Resources