✅ Extreme Newbie - Can't Call Class Element Properly.

Hello! I'll start off by kindly asking you don't laugh at my lack of knowledge. I am doing a 4 person group project alone because my teacher is a horrible person and I need help badly. I am trying to store variables in an array, and then allow the user to calculate the total cost of the stored variables by pressing that calculate button. I feel like I've gotten it all, I just can't get the button to call the sum properly and display it in the table. Any help at all would be appreciated more than you could possible imagine~ I'll post my full code below, as well as an image of what it currently outputs
80 Replies
Katt Does Art
Katt Does ArtOP3d ago
Code:
namespace Group_3_Project_Final
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}

DataTable table = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("Item Description");
table.Columns.Add("Order Quantity", typeof(int));
table.Columns.Add("Unit Price", typeof(int));

dataGridView1.DataSource = table;
}

private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}
public class Globals
{
public static void DisplayAndSum(decimal[] inputCostArray)
{
decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}
}
}

private void calculateBtn_Click(object sender, EventArgs e)
{
var totalSum = new Globals();
table.Rows.Add (totalSum);

}

private void clearBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource=null;
}
}
}
namespace Group_3_Project_Final
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{

}

DataTable table = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("Item Description");
table.Columns.Add("Order Quantity", typeof(int));
table.Columns.Add("Unit Price", typeof(int));

dataGridView1.DataSource = table;
}

private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}
public class Globals
{
public static void DisplayAndSum(decimal[] inputCostArray)
{
decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}
}
}

private void calculateBtn_Click(object sender, EventArgs e)
{
var totalSum = new Globals();
table.Rows.Add (totalSum);

}

private void clearBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource=null;
}
}
}
Angius
Angius3d ago
$code
MODiX
MODiX3d ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Angius
Angius3d ago
Not sure why you have that Globals class... inside of another class
Katt Does Art
Katt Does ArtOP3d ago
What happens:
No description
Katt Does Art
Katt Does ArtOP3d ago
Complete transparency, I've been working on this for like 10 hours, and I've been taking a lot of suggestions from google
Angius
Angius3d ago
Well, then, your DisplayAndSum() method does, effectively, nothing
Katt Does Art
Katt Does ArtOP3d ago
I feel very out of my depth here, but I have no one to really ask for help, Like I said my teacher isn't very... helpful
Angius
Angius3d ago
It takes an array of decimals, sums them, and... does nothing with the sum
Katt Does Art
Katt Does ArtOP3d ago
ah var totalSum = new Globals(); table.Rows.Add (totalSum); That's what I was trying to do here, but clearly I am not knowledgable enough to make it happen lmfao I am trying to display it to a new row basically I was trying to get the button to call the sum itself, but I was running into so many issues, this is the only way I could get it to work, so I thought I did it, and then it put this out lol Is there a way to properly call it that I'm missing? Or am I just doing it way wrong?
Angius
Angius3d ago
Well, you will have to get the array into this method Easiest way to have any data available to multiple methods is using a private field For example,
class Foo
{
private int _num;

public void Bar()
{
_num = 69;
}

public void Baz()
{
Console.WriteLine($"Number is {_num}");
}
}
class Foo
{
private int _num;

public void Bar()
{
_num = 69;
}

public void Baz()
{
Console.WriteLine($"Number is {_num}");
}
}
Katt Does Art
Katt Does ArtOP3d ago
I think that's what I was trying to accomplish but I wasn't able to pull the information out of the save area without an error
Angius
Angius3d ago
Bar here would be saveBtn_Click that creates the data, and Baz would be calculateBtn_Click that uses it
Katt Does Art
Katt Does ArtOP3d ago
That's why all the calculation stuff is there mmm okay, I think I understand So, Like this?
namespace Group_3_Project_Final
{
public partial class Form1 : Form
{


DataTable table = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("Item Description");
table.Columns.Add("Order Quantity", typeof(int));
table.Columns.Add("Unit Price", typeof(int));

dataGridView1.DataSource = table;
}

private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private void calculateBtn_Click(object sender, EventArgs e)
{
//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };

decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}
}

private void clearBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource=null;
}
}
}
namespace Group_3_Project_Final
{
public partial class Form1 : Form
{


DataTable table = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
table.Columns.Add("Item Description");
table.Columns.Add("Order Quantity", typeof(int));
table.Columns.Add("Unit Price", typeof(int));

dataGridView1.DataSource = table;
}

private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private void calculateBtn_Click(object sender, EventArgs e)
{
//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };

decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}
}

private void clearBtn_Click(object sender, EventArgs e)
{
dataGridView1.DataSource=null;
}
}
}
Or would I declare the variables outside calculate?
Angius
Angius3d ago
Where are you getting decimalQuantity and decimalPrice from?
No description
Angius
Angius3d ago
They're not local variables, not parameters, not fields
Katt Does Art
Katt Does ArtOP3d ago
The text boxes
Angius
Angius3d ago
They're local variables to saveBtn_Click
Katt Does Art
Katt Does ArtOP3d ago
//Variable declarations: string strDescription = textBoxItem.Text; decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text); decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);
Angius
Angius3d ago
They only exist within the {} of saveBtn_Click
Katt Does Art
Katt Does ArtOP3d ago
mmm how do I fix that?
Angius
Angius3d ago
That's what fields help with
Katt Does Art
Katt Does ArtOP3d ago
I think that's probably the root of my issue
Angius
Angius3d ago
class Foo
{
public void Bar()
{
int _num = 69;
}

public void Baz()
{
// `_num` does not exist here
Console.WriteLine($"Number is {_num}");
}
}
class Foo
{
public void Bar()
{
int _num = 69;
}

public void Baz()
{
// `_num` does not exist here
Console.WriteLine($"Number is {_num}");
}
}
class Foo
{
private int _num;

public void Bar()
{
_num = 69;
}

public void Baz()
{
// `_num` exists here
Console.WriteLine($"Number is {_num}");
}
}
class Foo
{
private int _num;

public void Bar()
{
_num = 69;
}

public void Baz()
{
// `_num` exists here
Console.WriteLine($"Number is {_num}");
}
}
$scopes
MODiX
MODiX3d ago
scope A {
thing a;
scope B {
thing b;
}
}
scope A {
thing a;
scope B {
thing b;
}
}
thing a is available in scope A and scope B thing b is available only in scope B
Angius
Angius3d ago
Braces create scopes. Things are only available in their scope and all child scopes
Katt Does Art
Katt Does ArtOP3d ago
right My confusion is how I would acomplish this Savebtn { inputs; CalcBtn { doing things w those inputs; } } Whenever I try to edit the set voids it breaks everything and I basically have to start over unless it's way more simple than I think and I'm just dumb which is possible lol Because from what I understand you can't nest voids into eachother Because they have to enter the information by pressing save
Angius
Angius3d ago
Wym "voids"?
Katt Does Art
Katt Does ArtOP3d ago
private void calculateBtn_Click(object sender, EventArgs e)
Angius
Angius3d ago
That's a method
Katt Does Art
Katt Does ArtOP3d ago
Sorry
Angius
Angius3d ago
$structure
MODiX
MODiX3d ago
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;

int LocalMethod(string param) { return 3; }
}
}
Katt Does Art
Katt Does ArtOP3d ago
I am starting to get lost I think. They are defined as methods by the program, I can not change that or it breaks everything
Angius
Angius3d ago
Never told you to change the methods Introduce a field To make data available in any method in the class
Angius
Angius3d ago
Presumably, you would like to have those two values in your calculateBtn_Click method, right?
No description
Katt Does Art
Katt Does ArtOP3d ago
Yeah
Angius
Angius3d ago
Turn them into fields Local variables are that: local Available only ever inside of the method they're in Not in any other method Fields are available in any method in the class So you can give them values inside of saveBtn_Click, and then use those values in calculateBtn_Click
Katt Does Art
Katt Does ArtOP3d ago
Okay, so Like that?
saveButtonClick calculations = new saveButtonClick();
{
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };
}
saveButtonClick calculations = new saveButtonClick();
{
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };
}
Angius
Angius3d ago
No, not whatsoever
Katt Does Art
Katt Does ArtOP3d ago
oh :keksob: sorry
Angius
Angius3d ago
Your code is currently equivalent to
void saveBtn_Click()
{
int a = 3;
int b = 4;
}

void calculateBtn_Click()
{
Print(a + b);
}
void saveBtn_Click()
{
int a = 3;
int b = 4;
}

void calculateBtn_Click()
{
Print(a + b);
}
a and b are not available in calculateBtn_Click
Katt Does Art
Katt Does ArtOP3d ago
Right
Angius
Angius3d ago
private int a;
private int b;

void saveBtn_Click()
{
a = 3;
b = 4;
}

void calculateBtn_Click()
{
Print(a + b);
}
private int a;
private int b;

void saveBtn_Click()
{
a = 3;
b = 4;
}

void calculateBtn_Click()
{
Print(a + b);
}
Now they are
Katt Does Art
Katt Does ArtOP3d ago
oh Okay, So, like that?
private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private decimal inputCost;
private decimal[] inputCostArray;


private void calculateBtn_Click(object sender, EventArgs e)
{
decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}

table.Rows.Add (sum);

}
private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
decimal inputCost = decimalQuantity * decimalPrice;
decimal[] inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private decimal inputCost;
private decimal[] inputCostArray;


private void calculateBtn_Click(object sender, EventArgs e)
{
decimal sum = 0;
foreach (var element in inputCostArray)
{
sum += element;
}

table.Rows.Add (sum);

}
Angius
Angius3d ago
Closer You still declare local variables instead of assigning to the fields Look at my examples and note the differences How int a = 3; turned into a = 3;
Katt Does Art
Katt Does ArtOP3d ago
I don't think I understand. Are you saying that's too specific or too broad? oh wait
private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
inputCost = decimalQuantity * decimalPrice;
inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private decimal inputCost;
private decimal[] inputCostArray;
private void saveBtn_Click(object sender, EventArgs e)
{
table.Rows.Add(textBoxItem.Text, textBoxQty.Text, textBoxUnit.Text);
dataGridView1.DataSource = table;

//Variable declarations:
string strDescription = textBoxItem.Text;
decimal decimalQuantity = Convert.ToDecimal(textBoxQty.Text);
decimal decimalPrice = Convert.ToDecimal(textBoxUnit.Text);


//calculate input cost and save to array
inputCost = decimalQuantity * decimalPrice;
inputCostArray = { inputCost };


//Clear boxes upon saving.
textBoxItem.Clear();
textBoxQty.Clear();
textBoxUnit.Clear();
}

private decimal inputCost;
private decimal[] inputCostArray;
I think I see what you meant instead of marking it as a decimal in the method, do it outside
Angius
Angius3d ago
Yep
Katt Does Art
Katt Does ArtOP3d ago
:D I got it to kind of work!!! It just displays 0 now though decimal sum = 0; foreach (var element in inputCostArray) { sum += element; } table.Rows.Add (sum); This would add together all the items in the array right?
Katt Does Art
Katt Does ArtOP3d ago
I am also getting this error, so I'm wondering if I didn't do this right
No description
Katt Does Art
Katt Does ArtOP3d ago
I think I'm moving in the right direction? I am having an issue here though decimal[] inputCostArray = inputCost; it says it can't convert decimal to decimal[]
Angius
Angius3d ago
Means you never give this field any value
Katt Does Art
Katt Does ArtOP3d ago
Yeah, I'm trying to now, I'm just struggling
Angius
Angius3d ago
Correct, inputCostArray is an array, stores multiple decimals inputCost is a single decimal
Katt Does Art
Katt Does ArtOP3d ago
How do I add the input to the array?
Angius
Angius3d ago
Here's how you used to have this code, and it was correct
No description
Katt Does Art
Katt Does ArtOP3d ago
That was giving an error though
Angius
Angius3d ago
Ah, well, might have to create the array explicitly then new decimal[] { inputCost } Or maybe [ inputCost ] Depending on the version of C#/.NET used, the latter is probably the better option
Katt Does Art
Katt Does ArtOP3d ago
I can try that Nope :/ C# 7.3 says I'd have to use version 12 or higher for the latter
Katt Does Art
Katt Does ArtOP3d ago
And then the first give this error
No description
Angius
Angius3d ago
inputCostArray = new decimal[] { inputCost } We're currently on C# 13, btw
Katt Does Art
Katt Does ArtOP3d ago
Idk how to upgrade, my teacher sent out a specific version for us to use But duly noted for once the class is over!
Angius
Angius3d ago
Yeah, if the teacher requires this one, use this one
Katt Does Art
Katt Does ArtOP3d ago
I'd like to learn more of this on my own with no strict timeframe
Angius
Angius3d ago
Chances are they wouldn't know the new features and mark them as errors lmao
Katt Does Art
Katt Does ArtOP3d ago
It looks like that worked, but still says will be null Honestly, 100%
Angius
Angius3d ago
Ah, it warns about null because, before the value gets assigned to this array, that's what it's going to be null, nothing Accessing elements of this array would be an error An easy way to handle it is just give the field a default value, empty array
private decimal[] inputCostArray = {};
private decimal[] inputCostArray = {};
should work If not,
private decimal[] inputCostArray = new decimal[]();
private decimal[] inputCostArray = new decimal[]();
Katt Does Art
Katt Does ArtOP3d ago
What is an initializer?
Angius
Angius3d ago
In what context?
Katt Does Art
Katt Does ArtOP3d ago
No description
Angius
Angius3d ago
Ah, duh Try
private decimal[] inputCostArray = Array.Empty<decimal>();
private decimal[] inputCostArray = Array.Empty<decimal>();
Katt Does Art
Katt Does ArtOP3d ago
Fixed the error, but still has the warning
Angius
Angius3d ago
Show it
Katt Does Art
Katt Does ArtOP3d ago
No description
Angius
Angius3d ago
Weird, the warning should not be there Maybe just VS being confused Happens
Katt Does Art
Katt Does ArtOP3d ago
I can try running it and see what it does
Angius
Angius3d ago
Yeah, it should build and run fine Give it a shot
Katt Does Art
Katt Does ArtOP3d ago
Let's you calculate, but gives the wrong answer so, half win lmfao Okay, looks like it only does the second calculation Okay, I think I know what's heppening I start by setting sum to 0, so it basically ignores the first thing entered I thought I knew how to fix it but I am once again stuck, sorry
Angius
Angius3d ago
Well, right now you're only calculating a single row Presumably, you want to calculate a total sum, right? If so, you will have to go over all rows of the datagrid
foreach (var item in dataGridView1.Items)
{
// ...
}
foreach (var item in dataGridView1.Items)
{
// ...
}
if I'm not mistaken
Katt Does Art
Katt Does ArtOP3d ago
Ah, that makes sense dataGridView1.Items? It says items isn't valid would it be .element? nope ayy I think I did it? :D
private void calculateBtn_Click(object sender, EventArgs e)
{
decimal sum = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (var element in inputCostArray)
{
sum += element;
}
}
table.Rows.Add(sum);
}
private void calculateBtn_Click(object sender, EventArgs e)
{
decimal sum = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (var element in inputCostArray)
{
sum += element;
}
}
table.Rows.Add(sum);
}
mm maybe not, because it should have given me 6 and I got 12 lol oh wait Nope, wasn't user error On the bright side, I think I've completed the final aisde from getting the wrong number 🤣 I am so close, but it just keeps giving me double. I feel like it's because of how I did this, but idk how to fix it I have to hop off for the day, but if you are back before me, I'd love to know what I'm doing wrong :KEK: This should hopefully be the last hurdle in coding before I finish it up!

Did you find this page helpful?