how to declare global function or method using c#? - 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);
}
}
}

Related

MEF based plugin system can't instance my plugins

I've implemented a very small plugin system based on C# with MEF. The problem is, none of my plugins are instanced. In the Aggregate-Catalog I can see my plugin listed. But, after I'll compose these parts, there isn't my plugin in the plugin list, what I'm doing wrong?
Here's a snippet of my code:
Plugin-Loader:
[ImportMany(typeof(IFetchService))]
private IFetchService[] _pluginList;
private AggregateCatalog _pluginCatalog;
private const string pluginPathKey = "PluginPath";
...
public PluginManager(ApplicationContext context)
{
var dirCatalog = new DirectoryCatalog(ConfigurationManager.AppSettings[pluginPathKey]);
//Here's my plugin listed...
_pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(_pluginCatalog);
compositionContainer.ComposeParts(this);
}
...
And here, the plugin itself:
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public MySamplePlugin()
{
Console.WriteLine("Plugin entered");
}
...
}
Tested working sample.
Compile class library with code inside PluginNameSpace namespace and place it to the 'Test' folder which will be inside console app exe folder.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using ConsoleApplication;
namespace ConsoleApplication
{
public interface IFetchService
{
void Write();
}
class PluginManager
{
[ImportMany(typeof(IFetchService))]
public IFetchService[] PluginList;
public PluginManager()
{
var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Test");
var pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(pluginCatalog);
compositionContainer.ComposeParts(this);
}
}
class Program
{
static void Main(string[] args)
{
var pluginManager = new PluginManager();
foreach (var fetchService in pluginManager.PluginList)
{
fetchService.Write();
}
Console.ReadKey();
}
}
}
// Separate class library
namespace PluginNameSpace
{
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public void Write()
{
Console.WriteLine("Plugin entered");
}
}
}

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.

How to call a method(function) to a form2 which is written in form1 in c#.net?

Of course there are many answers for this question,though,I got no clear Idea for my problem.
I'm working on Visual Studio.I have 2 forms as one is weeklyGVadminview and dailyGVadminview..
I wrote a function(method) in dailyGVadminview which is needed now in another form.....
I'm adding my code here..Any ansers will be appreciated in advance thanks.
namespace weeklyattendance
{
public partial class dailyGvAdminview : Form
{
public dailyGvAdminview()
{
InitializeComponent();
}
private void datechanges()
{
string date = dateTimePicker1.Value.ToString("dd/MM/yyyy");
var connectionstring = ConfigurationManager.ConnectionStrings["attendancemanagement"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionstring);
string query = "select count(Employee_id) from employee_details";
cn.Open();
SqlCommand cmd = new SqlCommand(query, cn);
object result =cmd.ExecuteScalar();
txttotalstaff.Text = (result.ToString());
cn.Close();
}
}
}
Form2 code as follows
namespace weeklyattendance
{
public partial class weeklyGvAdminView : Form
{
public weeklyGvAdminView()
{
InitializeComponent();
}
}
private void dateTimePicker1_ValueChanged_1(object sender, EventArgs e)
{
//here I want to call that function or method
}
}
So I would just create a new class and put the method on that class:
public class DbHandler
{
public string DateChanges()
{
string date = dateTimePicker1.Value.ToString("dd/MM/yyyy");
var connectionstring = ConfigurationManager.ConnectionStrings["attendancemanagement"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionstring);
string query = "select count(Employee_id) from employee_details";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
object result = cmd.ExecuteScalar();
var result = result.ToString();
conn.Close();
return result;
}
}
Then in your classes do this:
var dbHandler = new DbHandler();
var result = dbHandler.DateChanges();
I would try and follow some conventions as well. Makes it easier for other programmers to follow what is going on.
You can create object of dailyGvAdminview and call for that try below code :-
namespace weeklyattendance
{
public partial class weeklyGvAdminView : Form
{
public weeklyGvAdminView()
{
InitializeComponent();
}
}
private void dateTimePicker1_ValueChanged_1(object sender, EventArgs e)
{
var form1 = new dailyGvAdminview();
//// call function using this instance
}
}
If you want to access method from outside then make it to Public as shown below :-
public string DateChanges()
{
}
If you want a really GLOBAL and easy solution do this, first you make a static class.
namespace weeklyattendance
{
public static class Obj
{
public static dailyGvAdminview globalDaily;
}
}
Then in your initialize or onLoad code where you create this class just write
Obj.globalDaily = this;
Now you can access this class anywhere in your program with Obj.globalDaily, you can also add whatever else you want in there and access it like that

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

ToString() does not return the expected string

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3Generics
{
class Program
{
static void Main(string[] args)
{
ScheduleSelectedItems sitems = new ScheduleSelectedItems("Yusuf");
ScheduleSelectedItemsList slist = new ScheduleSelectedItemsList();
slist.Items.Add(sitems);
Console.Write(slist.Items[0].ToString());
Console.ReadKey();
}
}
public class ScheduleSelectedItems
{
private string Ad;
public ScheduleSelectedItems(string ad)
{
Ad = ad;
}
}
public class ScheduleSelectedItemsList
{
public List Items;
public ScheduleSelectedItemsList()
{
Items = new List();
}
}
}
how can i add "yusuf" on my Console?
public class ScheduleSelectedItems
{
private string Ad;
public ScheduleSelectedItems(string ad)
{
Ad = ad;
}
public override string ToString()
{
return this.Ad;
}
}
What BFree said, with a slight modification to make it singular instead of plural:
public class ScheduleSelectedItem
{
private string Ad;
public ScheduleSelectedItem(string ad)
{
Ad = ad;
}
public override string ToString()
{
return this.Ad;
}
}
Additionally, you want an "Add" method for your list. While you're at it, why not just inherit from the list class:
public class ScheduleSelectedItemsList : List<ScheduleSelectedItem>
{
}
Or you could just create a type alias:
using ScheduleSelectedItemsList = List<ScheduleSelectedItem>;
Either way, you can use the new code like this:
class Program
{
static void Main(string[] args)
{
var slist = new ScheduleSelectedItemsList()
{
new ScheduleSelectedItem("Yusuf")
};
//write every item to the console, not just the first
slist.All(item => Console.Write(item.ToString()) );
Console.ReadKey();
}
}
Add this to your ScheduleSelectedItems class:
public override string ToString() {
return Ad;
}
That tells the system how such an object should be formatted.
You need to override the toString() method of ScheduleSelectedItems to return 'Ad'.

Categories

Resources