0

I have a predicament! I don't know where I should put my variables in a C# Windows Forms Application. For example, in my WFA project I have a list of my own datatype object called "Item" and at the moment I've had to make it global, however, I understand global isn't the best of practises. Because I come from a C++ background I'd always create my variables in int main() and pass them to functions where needed. I honestly can't find an answer anywhere. Many thanks to anyone who can assist me.

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 Sales_Calculator
{
 
    public partial class Form1 : Form
    {
        //Should my list<Item> go here or is there a better place for it?
        List<Item> objItems = new List<Item>();
        public Form1()
        {
            InitializeComponent();
        }
        public class Item
        {
            private string m_sItemName;
            private double m_dItemPrice;
            private int m_iQuantitySold;

            public Item(string sItemName, double dItemPrice, int iQuantitySold)
            {
                m_sItemName = sItemName;
                m_dItemPrice = dItemPrice;
                m_iQuantitySold = iQuantitySold;
            }
            public string Name
            {
                get { return m_sItemName; }
                set { m_sItemName = value; }
            }
            public int QuantitySold
            {
                get { return m_iQuantitySold; }
                set { m_iQuantitySold = value; }
            }
            public double Price
            {
                get { return m_dItemPrice; }
                set { m_dItemPrice = value; }
            }
        }
        bool DoesItemNameExist(string sName)
        {
            return (objItems.Find(delegate (Item objItem){return sName == objItem.Name;}) != null) ? true : false;
        }
        private Item HighestSellingItem()
        {
            int MaxQuantitySold = objItems.Max(objItem => objItem.QuantitySold);
            return objItems.Find(delegate (Item objItem) {
                return objItem.QuantitySold == MaxQuantitySold;
            });
        }
        private double Average()
        {
            int iTotal = 0;
            objItems.ForEach(delegate (Item objItem)
            {
                iTotal += objItem.QuantitySold;
            });
            double dAverage = iTotal / objItems.Count;
            return dAverage;
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void AddToDataGridView(object sender)
        {
            dgvItems.Rows.Add(objItems.Count, objItems.Last().Name, objItems.Last().QuantitySold, objItems.Last().Price);
        }
        void ClearTextBoxes()
        {
            txtItemName.Clear();
            txtItemPrice.Clear();
            txtQuantitySold.Clear();
        }
        void AddItemToList()
        {
            
            string sItemName = "";
            if (DoesItemNameExist(sItemName = Convert.ToString(txtItemName.Text)))
            {
                MessageBox.Show("You can't have that name, it already exists!");
                txtItemName.Clear();
                return;
            }
            double dItemPrice = Convert.ToDouble(txtItemPrice.Text);
            int iQuantitySold = Convert.ToInt32(txtQuantitySold.Text);
            Item objItem = new Item(sItemName, dItemPrice, iQuantitySold);
            objItems.Add(objItem);
            MessageBox.Show("You have added an item!");
            ClearTextBoxes();
                
            
           
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
            AddItemToList();
            AddToDataGridView(sender);
            lblAverageQuantitySold.Text = Average().ToString();
            lblExistingItems.Text = objItems.Count.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("You have inputted incorrectly!", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            dvgHighestSellingItem.Rows.Clear();
            dvgHighestSellingItem.Rows.Add(HighestSellingItem().Name);
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
           

        }
    }
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • 1
    If the list is required only inside the Form class then you have it in the right place. However I suggest you to remove the internal Item class and move it to a different file in the same namespace. Finally all the methods like Average, HighestSellingItem and DoesItemNameExist are unnecessary because you have the same functionality in the system Linq namespace that I really advise you to explore and learn – Steve Nov 14 '20 at 19:27
  • But the functions are tailored to my own object. You're telling me there's a function called "DoesItemNameExist"? – George Austin Bradley Nov 14 '20 at 19:31
  • 1
    This line var item = _objItems.FirstOrDefault(x => x.Name == sName);_ will do the same of your DoesItemNameExists. If item == null then no match, else you have the item – Steve Nov 14 '20 at 19:33
  • 1
    _var item = objItems.OrderBy(x => x.QuantitySold).First();_ could replace HighestSellingItem – Steve Nov 14 '20 at 19:35
  • Oh I see what you mean! I've only just started to learn about C# after spending a lot of time in C++! I can already see endless possibilities in this language. Thanks very much! – George Austin Bradley Nov 14 '20 at 19:38
  • 1
    What you have learned in C++ will be of immense value in the Managed env. You just need to find the translations to the new world. – Steve Nov 14 '20 at 19:45
  • I need to correct the first comment: A more precise conversion for DoesItemNameExists would be: _bool exist = objItems,Any(x => x.Name == sName);_ – Steve Nov 14 '20 at 19:47
  • How to organize a program is largely an art and a subjective concern. That said, there are some best practices which you can and should follow, first and foremost being to ensure good "separation of concerns". Strategies like MVC, MVP, and MVVM (which IMHO are all basically the same) provide a paradigm to work in where you make sure that all your non-UI data goes in one place, and all the UI stuff somewhere else. See duplicates, and numerous other resources for information about these ideas. – Peter Duniho Nov 14 '20 at 21:25

0 Answers0