In Form1, why isn't myListBox displaying my name property inside of class Student
Form1
private static List<Student> studentListHome = new List<Student>();
...
public void BindData()
{
if (studentListHome != null)
{
studentListBox.DataSource = studentListHome;
studentListBox.DisplayMember = "name";
}
}
private void refreshButton_Click(object sender, EventArgs e)
{
BindData();
}
Student
private string name;
public string Name
{
get
{
return name;
}
}
...
public Student(string _name, int _id, string _bday)
{
name = _name;
id = _id;
bday = _bday;
}
Because 'name' is a private string.
Try using 'Name' which is your property.
studentListBox.DisplayMember = "Name";
This fixed it
Changing
studentListBox.DisplayMember = "Name";
To
foreach(Student s in studentListHome){
studentListBox.DisplayMember = "Name";
}
Related
I am making an inventory project, users can pick the category, put price, quantity, etc. but with customized exceptions. I'm trying to put all of these data into the DataGridView. I've checked and supposedly I should Declare the variable showProductList of BindSourceclass inside frmAddProduct. Instantiate the BindingSource class inside the constructor of frmAddProduct().
But how exactly?
(The error comes from showProductList, I think I am missing something, but I don't know what.)
this is what I have tried:
public partial class frmAddProduct : Form
{
private string _ProductName, _Category, _MfgDate, _ExpDate, _Description;
private int _Quantity;
private double _SellPrice;
public string Product_Name (string name)
{
if (!Regex.IsMatch(name, #"^[a-zA-Z]+$"))
try
{
}
catch (Exception StringFormattException)
{
}
finally
{
}
return name;
}
public int Quantity(string qty)
{
if (!Regex.IsMatch(qty, #"^[0-9]"))
try
{
}
catch (Exception NumberFormattException)
{
}
finally
{
}
return Convert.ToInt32(qty);
}
public double SellingPrice(string price)
{
if (!Regex.IsMatch(price.ToString(), #"^(\d*\.)?\d+$"))
try
{
}
catch (Exception CurrencyFormatException)
{
}
finally
{
}
return Convert.ToDouble(price);
}
public frmAddProduct()
{
InitializeComponent();
var showProductList = new BindingSource();
}
private void frmAddProduct_Load(object sender, EventArgs e)
{
string[] ListOfProductCategory = { "Beverages", "Bread/Bakery", "Canned/Jarred Goods", "Dairy", "Frozen Goods", "Meat", "Personal Care", "Other" };
foreach(string LPC in ListOfProductCategory)
{
cbCategory.Items.Add(LPC);
}
}
private void btnAddProduct_Click(object sender, EventArgs e)
{
_ProductName = Product_Name(txtProductName.Text);
_Category = cbCategory.Text;
_MfgDate = dtPickerMfgDate.Value.ToString("yyyy-MM-dd");
_ExpDate = dtPickerExpDate.Value.ToString("yyyy-MM-dd");
_Description = richtxtDescription.Text;
_Quantity = Quantity(txtQuantity.Text);
_SellPrice = SellingPrice(txtSellPrice.Text);
showProductList.Add(new ProductClass(_ProductName, _Category, _MfgDate, _ExpDate, _SellPrice, _Quantity, _Description));
gridViewProductList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
gridViewProductList.DataSource = showProductList;
}
}
this is the other class:
class ProductClass
{
private int _Quantity;
private double _SellingPrice;
private string _ProductName, _Category, _ManufacturingDate, _ExpirationDate, _Description;
public ProductClass(string ProductName, string Category, string MfgDate, string ExpDate, double Price, int Quantity, string Description)
{
this._Quantity = Quantity;
this._SellingPrice = Price;
this._ProductName = ProductName;
this._Category = Category;
this._ManufacturingDate = MfgDate;
this._ExpirationDate = ExpDate;
this._Description = Description;
}
public string productName
{
get
{
return this._ProductName;
}
set
{
this._ProductName = value;
}
}
public string Category
{
get
{
return this._Category;
}
set
{
this._Category = value;
}
}
public string manufacturingDate
{
get
{
return this._ManufacturingDate;
}
set
{
this._ManufacturingDate = value;
}
}
public string expirationDate
{
get
{
return this._ExpirationDate;
}
set
{
this._ExpirationDate = value;
}
}
public string description
{
get
{
return this._Description;
}
set
{
this._Description = value;
}
}
public int quantity
{
get
{
return this._Quantity;
}
set
{
this._Quantity = value;
}
}
public double sellingPrice
{
get
{
return this._SellingPrice;
}
set
{
this._SellingPrice = value;
}
}
class NumberFormattException : Exception
{
public NumberFormattException(string Quantity) : base(Quantity) { }
}
class StringFormattException : Exception
{
public StringFormattException(string Product_Name) : base(Product_Name) { }
}
class CurrencyFormatException : Exception
{
public CurrencyFormatException( string SellingPrice) : base(SellingPrice) { }
}
}
This line of code is not doing what you think it is doing…
showProductList.Add(new ProductClass(_ProductName, _Category, _MfgDate, _ExpDate, _SellPrice, _Quantity, _Description));
showProductList is a BindingSource and you need to set its DataSource property.
A BindingList<ProductClass> or a List<ProductClass> or even a DataTable will work as a DataSource for the BindingSource.
With this new “list”, the code “adds” the items to this list, then simply calls the BindingSources.ResetBindings(false) to update the grid.
Example:
Add these global variables to the form…
BindingSource ProductsBS;
BindingList<ProductClass> ListOfProducts;
Update the forms constructor to initialize the binding source and set its data source….
public Form1() {
InitializeComponent();
ProductsBS = new BindingSource();
ListOfProducts = new BindingList<ProductClass>();
ProductsBS.DataSource = ListOfProducts;
gridViewProductList.DataSource = ProductsBS;
gridViewProductList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
Finally, change the button click event code like…
private void btnAddProduct_Click(object sender, EventArgs e) {
_ProductName = Product_Name(txtProductName.Text);
_Category = cbCategory.Text;
_MfgDate = dtPickerMfgDate.Value.ToString("yyyy-MM-dd");
_ExpDate = dtPickerExpDate.Value.ToString("yyyy-MM-dd");
_Description = richtxtDescription.Text;
_Quantity = Quantity(txtQuantity.Text);
_SellPrice = SellingPrice(txtSellPrice.Text);
ListOfProducts.Add(new ProductClass(_ProductName, _Category, _MfgDate, _ExpDate, _SellPrice, _Quantity, _Description));
ProductsBS.ResetBindings(false);
}
I hope this makes sense.
i am updating my question to this
i created new class Student
class Student
{
private string _firstName;
private string _lastName;
private int _exam1;
private int _exam2;
private int _exam3;
private int _finalExam;
// First Name Property
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
//Last Name Property
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
//Exam 1 Property
public int Exam1
{
get { return _exam1; }
set { _exam1 = value; }
}
// Exam 2 Property
public int Exam2
{
get { return _exam2; }
set { _exam2 = value; }
}
//Exam 3 Property
public int Exam3
{
get { return _exam3; }
set { _exam3 = value; }
}
//Final Exam Property
public int FinalExam
{
get { return _finalExam; }
set { _finalExam = value; }
}
}
}
this is my add new student form class with one method to add new student
public class AddStudent : Form
{
StudentForm stu = null;
public AddStudent()
{
InitializeComponent();
stu = new StudentForm();
stu.Show();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// split the name into first and last name
string[] name = txtName.Text.Split(',');
Student std = new Student();
std.FirstName = name[0];
std.LastName = name[1];
std.Exam1 = Int32.Parse(txtExam1.Text);
std.Exam2 = Int32.Parse(txtExam2.Text);
std.Exam3 = Int32.Parse(txtExam3.Text);
std.FinalExam = Int32.Parse(txtFinal.Text);
stu.addItem(std);
this.Hide();
}
}
}
and this is my main form it has listbox to display list of students
public class StudentForm : Form
{
public StudentForm()
{
InitializeComponent();
}
public List<Student> students = new List<Student>();
public void addItem(Student std)
{
students.Add(std);
// it always show me 1 item in list
MessageBox.Show(students.Count.ToString());
}
}
Here's how your code is progressing, with comments added and irrelevant code removed:
private void btnSubmit_Click(object sender, EventArgs e)
{
...
// create a _new_ Student form
Student std = new Student();
...
// Add the student form to itself (huh?)
std.addItem(std);
// hide this form
this.Hide();
// show the new form
std.Show();
}
So you are always showing a new form with one item - the one that was just created.
Yeah that's cause in your btnSubmit_Click every time you are creating a new instance of the form Student and calling the addItem() method.
You rather move this field to a separate class like
public class Data
{
private string _firstName;
private string _lastName;
private int _exam1;
private int _exam2;
private int _exam3;
private int _finalExam;
}
have the form instance created in the start up like
public partial class AddStudent : Form
{
Student stu = null;
public AddStudent()
{
InitializeComponent();
stu = new Student();
stu.Show();
}
Change the list in Form1
public List<Data> students = new List<Data>();
In button click just add the Data instance like
private void btnSubmit_Click(object sender, EventArgs e)
{
// split the name into first and last name
string[] name = txtName.Text.Split(',');
Data std = new Data();
std.FirstName = name[0];
std.LastName = name[1];
std.Exam1 = Int32.Parse(txtExam1.Text);
std.Exam2= Int32.Parse(txtExam2.Text);
std.Exam3 = Int32.Parse(txtExam3.Text);
std.FinalExam = Int32.Parse(txtFinal.Text);
stu.addItem(std);
this.Hide();
}
This is because you're creating the Student form each time using this line:
Student std = new Student();
So every time you're clicking submit, you're creating a new Student form which creates a new empty public List<Student>
You need to seperate your model (Student) from your UI (StudentForm) and (AddStudentForm):
public class Student
{
public string FirstName { set; get; }
private string LastName { set; get; }
private int Exam1 { set; get; }
private int Exam2 { set; get; }
private int Exam3 { set; get; }
private int FinalExam { set; get; }
}
You don't need to create a new StudentForm each time you add a Student. Instead, you can have one StudentForm and use ShowDialog() when navigating to the Addition Screen, this you go back to the same instance of StudentForm.
Try removing the Class Student instantiation out of the event - btnSubmit_Click event
Student std = new Student();
I have made a list and the data is added into the list by the user using textboxes and comboboxes, I am now trying to enter this list of data into a listbox but everytime I try to add the data I get the output as the class name e.g WindowApplicaion.Journey or it comes out as System.Collections.Generic.List`1[WindowApplication.Journey], i'm not sure if this is due to me placing the conversion code in the wrong place or i'm just doing it all wrong, here is my code for both cases:
private void ShowAllToursbttn_Click(object sender, RoutedEventArgs e)
{
foreach (Tour t in company.tours)
{
string converter = company.tours.ToString();
ToursListBox.Items.Add(converter);
}
}
or
private void ShowAllToursbttn_Click(object sender, RoutedEventArgs e)
{
foreach (Tour t in company.tours)
{
string ConvertedList = string.Join(" ", company.tours);
TourListBox.Items.Add(ConvertedList);
}
}
Where tours is my list I created in my company class and t is each instance in the list, any advice would be great, thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowApplication
{
class Tour
{
private string custFirstname;
private string custSurname;
private string custAddress;
private string pickupArea;
private string pickupDateandTime;
private string pickupDescription;
private string destinationArea;
private string destinationDescription;
//Creating getters and setters for each attribute
#region getters/setters
public string firstname
{
get { return custFirstname; }
set { custFirstname = value; }
}
public string surname
{
get { return custSurname; }
set { custSurname = value; }
}
public string address
{
get { return custAddress; }
set { custAddress = value; }
}
public string pickuparea
{
get { return pickupArea; }
set { pickupArea = value; }
}
public string pickupdateandtime
{
get { return pickupDateandTime; }
set { pickupDateandTime = value; }
}
public string pickupescription
{
get { return pickupDescription; }
set { pickupDescription = value; }
}
public string destinationarea
{
get { return destinationArea; }
set { destinationArea = value; }
}
public string destinationdescription
{
get { return destinationDescription; }
set { destinationDescription = value; }
}
}
}
That is my Tour class.
private void AddThisTourbttn_Click(object sender, RoutedEventArgs e)
{
Tour t = new Tour();
t.firstname = CustomerFirstnameTxt.Text;
t.surname = CustomerSurnameTxt1.Text;
t.address = CustomerAddressTxt.Text;
t.pickupdateandtime = TourDateTimeTxt.Text;
t.pickuparea = TourPickupArea.Text;
t.pickupescription = TourPickupDescriptionTxt.Text;
t.destinationarea = TourDestinationArea.Text;
t.destinationdescription = TourDestinationDescriptionTxt.Text;
company.addTour(t);
}
and on my MainWindow I have assigned each textbox to its appropriate get/set.
Your program displaying class name in listbox because you use default object's toString() method in ShowAllToursbttn_Click, which will output class name. Try to override ToString() method in Tour class, to output string with your desired format for example:
public override string ToString()
{
return String.Format("Firstname: {0}; Surname: {1}", firstname, surname);
}
And change ShowAllToursbttn_Click logic to:
private void ShowAllToursbttn_Click(object sender, RoutedEventArgs e)
{
foreach (Tour t in company.tours)
{
TourListBox.Items.Add(t.ToString());
}
}
I'm trying to get all the names in a list and display them in a listbox. Here's my code.
namespace UniRecords
public partial class MainWindow
{
private University uni = new University(); //Creates a new University object
public MainWindow()
{
InitializeComponent();
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
Student newStudent = new Student(txtname.Text, txtaddress.Text, txtmatric.Text,txtcourse.Text); //Calls the student constructor to construct a student object
uni.ownsStudent(newStudent); //Calls the newStudent method in the University class
}
private void btnshow_Click(object sender, RoutedEventArgs e)
{
uni.showStudents(); //calls the showStudents method
}
private void btnlist_Click(object sender, RoutedEventArgs e)
{
}
}
}
My University class:
namespace UniRecords
class University
{
//Creates a list of students that University owns
private List<Student> owns = new List<Student>();
public University()
{
}
public void ownsStudent(Student newStudent)
{
owns.Add(newStudent);//Adds a new student to the list
}
public void showStudents()
{
foreach (Student s in owns)
{
System.Windows.MessageBox.Show(s.printDetails()); //Prints out details of each student individually
}
}
public void getStudents()
{
foreach (Student s in owns)
{
}
}
}
}
Student class:
namespace UniRecords
class Student
{
private string name;
private string dob; //Date of birth
private string course;
private string matric;
private string address;
//Constructor
public Student(string myname, string myaddress, string mymatric, string mycourse)
{
Name = myname;
Address = myaddress;
Matric = mymatric;
Course = mycourse;
}
//Uses get and set to make sure that the variables are kept private
public string Name
{
get { return name; }
set { name = value; }
}
public string Dob
{
get { return dob; }
set { dob = value; }
}
public string Course
{
get { return course; }
set { course = value; }
}
public string Matric
{
get { return matric; }
set { matric = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string printDetails()
{
return "student is called " + Name + " " + Address + " " + Matric + " " + Course;
}
public void listNames()
{
}
}
}
I'm trying to have btnlst_click be pressed and get output a list of all the names that have been inputted.
I know I need to use something like: foreach (Student s in owns) but I don't have permissions to do it from the mainwindow class and I'm not sure how I could pass it from the University class to mainwindow to be put in the string. Can someone offer advice?
You have to define your method to have it return a list of studentnames.
public List<string> GetStudents(){
return owns.Select(x => x.Name).ToList();
}
This roughly translates to
public List<string> GetStudents(){
var result = new List<String>();
foreach(var student in owns) {
result.add(student.Name);
}
return result;
}
This small LINQ expression will select all the names of the students and return it for you to use. Notice the List<string> return statement instead of void.
And in your main form class:
myListBox.DataSource = someUniversity.GetStudents():
I'm not familiar with GUI development in C#, so this assignment might look different.
Keep naming conventions in mind: methods are CamelCased!
I am experiencing some problems while setting ValueMember property of my ComboBox.
The line comboBox1.ValueMember = "Code"; breaks my code.
Here is my code:
Form1.cs:
private void Form1_Load(object sender, EventArgs e) {
...
...
MAPList MAP = new MAPList();
comboBox1.DataSource = MAP.All;
comboBox1.ValueMember = "Code";
...
...
}
MAPList.cs:
public class MAPList {
public readonly List<MAP> All;
public MAPList() {
All = new List<MAP>();
var MapData = // Getting map data
foreach(MAP m in MapData) {
All.Add(new Map(m.Name, m.Code));
}
}
}
MAP.cs:
public class MAP {
public readonly string Name;
public readonly string Code;
public RadioCode(string name, string code) {
Name = name;
Code = code;
}
public override string ToString() {
return String.Format("{0}: {1}", Name, Code);
}
}
Try converting Code as a Property instead of a member and then binding it