I want to add Mark1,Mark2,Mark3,Mark4,Mark5 and assign it to the Sum to show in the gridview.
i want to add those marks through any function and assign it to the Sum property. how to do it? thanks
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void procees()
{
List<student> ml= new List<student>();
student s1 = new student() {
Name = "ram",
Id = "gn01",
Mark1 = 90,
Mark2 = 89,
Mark3 = 75,
Mark4 = 45,
Mark5 = 65,
Sum = ""
};
ml.Add(s1);
dataGridView1.DataSource = ml;
}
private void button1_Click(object sender, EventArgs e)
{
procees();
}
}
public class student
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private int mark1;
public int Mark1
{
get { return mark1; }
set { mark1 = value; }
}
private int mark2;
public int Mark2
{
get { return mark2; }
set { mark2 = value; }
}
private int mark3;
public int Mark3
{
get { return mark3; }
set { mark3 = value; }
}
private int mark4;
public int Mark4
{
get { return mark4; }
set { mark4 = value; }
}
private int mark5;
public int Mark5
{
get { return mark5; }
set { mark5 = value; }
}
private int sum;
public int Sum
{
get { return sum; }
set { sum = value; }
}
}
Remove private field 'sum':
private int sum;
Let the pubic property 'Sum' to calculate the sum:
public int Sum
{
get { return Mark1 + Mark2 + Mark3 + Mark4 + Mark5; }
}
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 need help with this code. If you run the code you'll get in the last 7 lines (which is for...loop for Order object) Exercise.OrderItem.The problem is that I would like to access the OrderItem objects with for...loop but all I get are the last 7 lines representing OrderItem objects.How can I access them in for...loop so that I get the same as in foreach...loop? I think it has something to do with the indexer.Thank You.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Exercise
{
interface IPricing
{
//read/write property
double Price
{
get;
set;
}
double Discount
{
get;
set;
}
}
public class Order:IPricing
{
private string name;
private double price;
private static int OrderNo;
//private ArrayList m_items = new ArrayList();
private ArrayList m_items;
//static constructor
static Order()
{
OrderNo = 0;
}
//default constructor
public Order()
{
name = null;
price = 0;
OrderNo++;
m_items = new ArrayList();
}
//constructor with parameters
public Order(string name, double price)
{
this.name = name;
this.price = price;
OrderNo++;
this.m_items = new ArrayList();
}
//copy constructor
public Order(Order order)
{
this.name = order.name;
this.price = order.price;
this.m_items = order.m_items;
}
public string Name
{
get { return name; }
set { name = value; }
}
public IEnumerable Items
{
get { return m_items; }
private set { }
}
public void AddItem(OrderItem orderItem)
{
orderItem.Order = name;
m_items.Add(orderItem);
}
public static Order operator +(Order o1, Order o2)
{
Order o3 = new Order(o1.name+", "+o2.name,o1.price+o2.price);
o3.m_items.AddRange(o1.m_items);
o3.m_items.AddRange(o2.m_items);
return o3;
}
//indexer
public object this[int index]
{
get
{
m_items[index] = this.m_items[index];
return m_items[index];
}
set { m_items[index] = value; }
}
public double ItemCount
{
get { return m_items.Count; }
private set{}
}
public virtual void Print()
{
Console.WriteLine("*********************Order No. {0}***********************", OrderNo);
Console.WriteLine("Details");
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Price: {0}", price);
}
public double Price
{
get { return price - Discount; }
set { price = value; }
}
public virtual double Discount
{
get { return 0; }
set { ;}
}
public void PrintItems()
{
Console.WriteLine("Items in this order: ");
Console.WriteLine();
foreach(OrderItem itm in this.m_items)
{
Console.WriteLine("Item name: {0,4};\tPart of order: {1}", itm.Name, itm.Order);
}
}
}
public class OrderItem
{
private string m_name; //name of the item in order
private string m_order; //name of the order whose parts are items with names m_name
//default constructor
public OrderItem()
{
m_order = null;
}
//parameter constructor
public OrderItem(string name)
{
this.m_name = name;
this.m_order = null;
}
//copy constructor
public OrderItem(OrderItem orderItem)
{
this.m_name = orderItem.m_name;
this.m_order = orderItem.m_order;
}
//Name read/write property
public string Name
{
get { return m_name; }
set { m_name = value; }
}
//Order read/write property
public string Order
{
get { return m_order; }
set { m_order = value; }
}
}
public class MainProgram
{
static void Main(string[] args)
{
string order1 = "Desktop PC";
Order desktopPC = new Order(order1,25000);
desktopPC.AddItem(new OrderItem("pc mouse"));
desktopPC.AddItem(new OrderItem("keyboard"));
desktopPC.AddItem(new OrderItem("monitor"));
desktopPC.AddItem(new OrderItem("pc"));
desktopPC.Print();
desktopPC.PrintItems();
Console.WriteLine();
string order2 = "Notebook";
Order notebook = new Order(order2, 54000);
notebook.AddItem(new OrderItem("mouse"));
notebook.AddItem(new OrderItem("bag"));
notebook.AddItem(new OrderItem("notebook"));
notebook.Print();
notebook.PrintItems();
Console.WriteLine();
Order total = desktopPC + notebook;
total.Print();
total.PrintItems();
Console.WriteLine();
Console.WriteLine("Getting the items via for loop");
for (int k = 0; k < total.ItemCount; k++)
{
Console.WriteLine(total[k]);
}
Console.ReadKey();
}
}
}
for (int k = 0; k < total.ItemCount; k++)
{
var x = total[k] as OrderItem;
if (x == null) continue;
Console.WriteLine(x.Name);
Console.WriteLine(x.Order);
}
I have a table (called !test) containing the following data:
id code desc
0 55 fifty-five
1 66 sixty-six
2 100 hundred
When I use the following code to access that table, it compiles & runs OK,
but doesn't populate the Tuple structure.
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.!test")]
public partial class Test
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ID;
private TupleClass _Tuple;
public Test()
{
_Tuple = new TupleClass();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", DbType="Int NOT NULL", IsPrimaryKey=true)]
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this._ID = value;
}
}
}
public TupleClass Tuple
{
get
{
return this._Tuple;
}
set
{
if ((this._Tuple.Code != value.Code))
{
this._Tuple.Code = value.Code;
}
if ((this._Tuple.Desc != value.Desc))
{
this._Tuple.Desc = value.Desc;
}
}
}
}
public class TupleClass
{
private int _Code;
private string _Desc;
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Code", DbType = "Int NOT NULL")]
public int Code
{
get
{
return this._Code;
}
set
{
if ((this._Code != value))
{
this._Code = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_Desc", DbType = "NVarChar(50)")]
public string Desc
{
get
{
return this._Desc;
}
set
{
if ((this._Desc != value))
{
this._Desc = value;
}
}
}
}
Any ideas what I've done wrong here? Thanks
I am totally unable to access the outer class attributes inside the inner class ...
even if i make object of outer class,, in inner class*which makes no sense in composition design* .. even then i cant access them ..
is there a way by which i can access these outer class attributes ?
Scenario is that there is some sports car which is constructed only if the customers who want to buy it exists! ..
namespace composition{
public class CustomCar
{
#region Attributes
private string name;
private string plateno;
private double cost;
private CarCustomer _customer = new CarCustomer();
#endregion
#region properties
public string Name
{
get { return name; }
set { name = value; }
}
public double Cost
{
get { return cost; }
set { cost = value; }
}
public string PlateNo
{
get { return plateno; }
set { plateno = value; }
}
public CarCustomer Customer
{
get { return _customer; }
set { _customer = value; }
}
#endregion
#region methods
public CustomCar()
{
Console.WriteLine("I am in custom car");
}
public CustomCar(string s1, string pno, double c, string s2, double n, double bc)
{
this.Name = s1;
this.PlateNo = pno;
this.Cost = c;
this.Customer.Name1 = s2;
this.Customer.Nic1 = n;
this.Customer.BargainCost = bc;
}
public double finalCost()
{
if (this.Customer.BargainCost < 10000)
{
double FinalCost = (this.Cost - this.Customer.BargainCost);
return FinalCost;
}
else
{
return this.Cost;
}
}
public void show()
{
Console.WriteLine(this.name + this.PlateNo + this.Customer.Name1 + this.Customer.Nic1);
}
#endregion
public class CarCustomer
{
private string name1;
private double Nic;
private double bargainCost;
public double BargainCost
{
get { return bargainCost; }
set { bargainCost = value; }
}
public double Nic1
{
get { return Nic; }
set { Nic = value; }
}
public string Name1
{
get { return name1; }
set { name1 = value; }
}
public CarCustomer()
{
Console.WriteLine("I have a customer");
}
public CarCustomer(string n1, double i1, double bc)
{
this.Name1 = n1;
this.Nic = i1;
this.BargainCost = bc;
}
public void showCustomer()
{
Console.WriteLine("Customer name: " + Name1);
Console.WriteLine("Customer NIC: " + Nic1);
}
}
}
}
There is nothing stopping you having a reference in the CarCustomer to the CustomCar object as well. This would then give you a one to one reference between the object. Were you instaiate this object is up to you in the Constructor of the CustomCar
public CustomCar(arguments)
{
this.Customer.CustomCar = this;
}
Or you could set it in the sets on the property accessors up to you. Try this
public class CustomCar
{
private string name;
private string plateno;
private double cost;
private CarCustomer _customer = new CarCustomer();
public string Name
{
get { return name; }
set { name = value; }
}
public double Cost
{
get { return cost; }
set { cost = value; }
}
public string PlateNo
{
get { return plateno; }
set { plateno = value; }
}
public CarCustomer Customer
{
get { return _customer; }
set { _customer = value; }
}
public CustomCar()
{
Console.WriteLine("I am in custom car");
}
public CustomCar(string name, string pno, double c, string customerName, double n, double bc)
{
this.Name = name;
this.PlateNo = pno;
this.Cost = c;
this.Customer.Name1 = customerName;
this.Customer.Nic1 = n;
this.Customer.BargainCost = bc;
this.Customer.Car = this;
}
public double finalCost()
{
if (this.Customer.BargainCost < 10000)
{
double FinalCost = (this.Cost - this.Customer.BargainCost);
return FinalCost;
}
else
{
return this.Cost;
}
}
public void show()
{
Console.WriteLine(this.name + this.PlateNo + this.Customer.Name1 + this.Customer.Nic1);
}
}
public class CarCustomer
{
private string name1;
private double Nic;
private double bargainCost;
private CustomCar customer;
public double BargainCost
{
get { return bargainCost; }
set { bargainCost = value; }
}
public double Nic1
{
get { return Nic; }
set { Nic = value; }
}
public string Name1
{
get { return name1; }
set { name1 = value; }
}
public CustomCar Car
{
get{return customer;}
set{customer = value;}
}
public CarCustomer()
{
Console.WriteLine("I have a customer");
}
public CarCustomer(string n1, double i1, double bc)
{
this.Name1 = n1;
this.Nic = i1;
this.BargainCost = bc;
}
public void showCustomer()
{
Console.WriteLine("Customer name: " + Name1);
Console.WriteLine("Customer NIC: " + Nic1);
}
}
Of course you can't access them. You've set their protection level to private. In order to get at them from an external resource their protection level has to be in line with the access level needed. In this case you should be able to change the modifier to protected and be able to access them.
However, looking at your class design, I think you would be better served using the automatic getter/setter syntax. You aren't doing anything particularly special in your property definitions, so it would make sense to get rid of the private variables and change your properties to this:
public string Name { get; set; }
public double Cost { get; set; }
public string PlateNo { get; set; }
public CarCustomer Customer { get; set; }
You'll still have public access to the variables through the properties and you won't have all the messiness of the extra variables.
I've been trying for hours to get many-to-many relationship to save with Castle ActiveRecord. What am I doing wrong? I can't find anything in the documentation or on google. There is data in the database.
Courses have a many to many relationship with Books.
Test code.
Database.Course c = new Database.Course();
c.Number = "CS 433";
c.Name = "Databases";
c.Size = 34;
c.Books = Database.Book.FindAll();
c.Save();
Also doesn't work
foreach(Database.Book b in Database.Book.FindAll()){
c.Books.Add(b);
}
Database Classes
[ActiveRecord]
public class Course : ActiveRecordValidationBase<Course>
{
private int? id;
private string number;
private string name;
private string description;
private int size; //number of students in class
//references
private IList books = new ArrayList();
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
get
{
return string.Format("{0} - {1}", Number, Name);
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Number
{
get { return number; }
set { number = value; }
}
[Property, ValidateNonEmpty]
public string Name
{
get { return name; }
set { name = value; }
}
[Property(ColumnType="StringClob")]
public string Description
{
get { return description; }
set { description = value; }
}
[Property]
public int Size
{
get { return size; }
set { size = value; }
}
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id", Inverse = true)]
public IList Books
{
get { return books; }
set { books = value; }
}
}
[ActiveRecord]
public class Book : ActiveRecordValidationBase<Book>
{
private int? id;
private string title;
private string edition;
private string isbn;
private bool is_available_for_order;
//relations
private IList authors = new ArrayList();
private IList bookordercount = new ArrayList();
private IList courses = new ArrayList();
private Inventory inventory;
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
//*
get {
string str;
if (Edition == null || Edition == "")
str = Title;
else
str = string.Format("{0} ({1})", Title, Edition);
if (Authors.Count != 0)
{
return string.Format("{0} by {1}", str, FormattedAuthors);
}
else
{
return str;
}
}
/*/
get
{
return Title;
}
//*/
}
public string FormattedAuthors
{
get
{
if (Authors.Count == 0) return "";
StringBuilder sb = new StringBuilder();
int i = 0, end = Authors.Count;
foreach (Author a in Authors)
{
i++;
sb.Append(a.FormattedName);
if (i != end) sb.Append("; ");
}
return sb.ToString();
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Title
{
get { return title; }
set { title = value; }
}
[Property]
public string Edition
{
get { return edition; }
set { edition = value; }
}
[Property, ValidateNonEmpty]
public string Isbn
{
get { return isbn; }
set { isbn = value; }
}
[Property]
public bool IsAvailableForOrder
{
get { return is_available_for_order; }
set { is_available_for_order = value; }
}
//relations
[HasAndBelongsToMany(typeof(Author),
Table = "BookAuthor", ColumnKey = "book_id", ColumnRef = "author_id")]
public IList Authors
{
get { return authors; }
set { authors = value; }
}
[HasMany(typeof(BookOrderCount), Table = "BookOrderCounts", ColumnKey = "BookId")]
public IList BookOrderCount
{
get { return bookordercount; }
set { bookordercount = value; }
}
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id")]
public IList Courses
{
get { return courses; }
set { courses = value; }
}
[OneToOne]
public Inventory Inventory
{
get { return inventory; }
set { inventory = value; }
}
}
Make sure you put the Inverse = true where you want it. From the Castle AR docs,
It is wise to choose one side of the
relation as the owner. The other side,
the non-writable, need to use
Inverse=true.
Put the Inverse = true on the other side of the relationship, like this:
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id")]
public IList<Book> Books
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id", Inverse = true)]
public IList<Course> Courses
You also have to add attributes to the top of both classes - at the moment they don't know what tables they're mapped to. Currently you have this:
public class Course : ActiveRecordBase<Course>
Add this (where "course" is the name of your Course table):
[ActiveRecord("course")]
public class Course : ActiveRecordBase<Course>