Error: "The name '(variable)' does not exist in the current context" - c#

Creating a new instance of Cost:
Cost newCost = new Cost();
newCost.TotalCost = 0;
newCost.Event = 1000;
newCost.personalEvent = 1500;
newCost.organisationalEvent = 1700;
then the if statement below it:
if (EventList.SelectedItem == "Event")
{
TotalCost = (Event + 100);
}
else if (EventList.SelectedItem == "Personal")
{
TotalCost = (personalEvent + 150);
}
else if (EventList.SelectedItem == "Organisational")
{
TotalCost = (organisationalEvent + 170);
}
else
{
txtTotalCost.Text = ("£" + TotalCost.ToString());
}
I also have a class named Cost, but i keep getting an error saying "The name 'TotalCost' does not exist in the current context".
Any help would be really appreciated.
My Cost class is as follows:
class Cost
{
public int TotalCost;
public int Event;
public int personalEvent;
public int organisationalEvent;
}

If you are trying to access the TotalCost field in your class, you need to provide an instance reference so that the computer knows from what object to read the value.
Replace TotalCost in the code with newCost.TotalCost.
if (EventList.SelectedItem == "Event")
{
newCost.TotalCost = (Event + 100);
}
else if (EventList.SelectedItem == "Personal")
{
newCost.TotalCost = (personalEvent + 150);
}
else if (EventList.SelectedItem == "Organisational")
{
newCost.TotalCost = (organisationalEvent + 170);
}
else
{
txtTotalCost.Text = ("£" + newCost.TotalCost.ToString());
}
By the way, it's not clear to me why you set txtTotalCost.Text only if you have not set the TotalCost field value. I would expect at a minimum that it's when you do set the TotalCost field value that you would want to update the txtTotalCost.Text property, and probably it makes sense to just always set it.

Related

Datagridview Dynamic cell calculation

I have two columns in Datagridview, one for the price excluding Vat and another one for price including Vat, I want it to be dynamic, if I alter the price excluding vat it updates the column including Vat, and if I Update the including Vat column it updates the excluding VAT column vice-versa.
I would appreciate if anyone can help me with the right code for it in C#.
Here´s the code I´m using the calculation to one direction I need the code for the inverse.
private void dgv_Filho_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
bool Check = Convert.ToBoolean(dgv_Filho.CurrentRow.Cells["Check_Filho"].Value);
string Medida_1 = Convert.ToString(dgv_Filho.CurrentRow.Cells["Medida_1"].Value);
string Medida_2 = Convert.ToString(dgv_Filho.CurrentRow.Cells["Medida_2"].Value);
var Iva = Convert.ToDecimal(cb_Iva.Text);
if (Check)
{
if (!string.IsNullOrWhiteSpace(tb_CodigoArtigo.Text) || !string.IsNullOrWhiteSpace(tb_Descricao.Text))
{
dgv_Filho.CurrentRow.Cells["ArtigoPai"].Value = tb_CodigoArtigo.Text;
dgv_Filho.CurrentRow.Cells["Descricao_Pai"].Value = tb_Descricao.Text + " " + Medida_1 + Medida_2;
dgv_Filho.CurrentRow.Cells["CodigoArtigoFilho"].Value = tb_CodigoArtigo.Text + Medida_1 + Medida_2;
//dgv_Filho.CurrentRow.Cells["PrecoFilhoSemIva"].Value = tb_PVP1.Text;
decimal PrecoFilho = Convert.ToDecimal(dgv_Filho.CurrentRow.Cells["PrecoFilhoSemIva"].Value);
if (PrecoFilho > 0)
{
decimal PrecoFilhoComIva = PrecoFilho * Iva / 100 + PrecoFilho;
dgv_Filho.CurrentRow.Cells["PrecoFilhoComIva"].Value = PrecoFilhoComIva;
}
}
else
{
dgv_Filho.CurrentRow.Cells["ArtigoPai"].Value = string.Empty;
dgv_Filho.CurrentRow.Cells["Descricao_Pai"].Value = string.Empty;
}
}
}
This isn't too difficult using your existing code:
First of all, use the name of the edited column in if/else if statements to filter which conversion should take place, so that changing the VAT column doesn't get overwritten by the preVAT column. Then, use the opposite algebraic expression of the one you already have written to convert the postVAT price back to the preVAT
Here is what it will look like:
dgv_Filho.CurrentRow.Cells["ArtigoPai"].Value = tb_CodigoArtigo.Text;
dgv_Filho.CurrentRow.Cells["Descricao_Pai"].Value = tb_Descricao.Text + " " + Medida_1 + Medida_2;
dgv_Filho.CurrentRow.Cells["CodigoArtigoFilho"].Value = tb_CodigoArtigo.Text + Medida_1 + Medida_2;
decimal PrecoFilho = Convert.ToDecimal(dgv_Filho.CurrentRow.Cells["PrecoFilhoSemIva"].Value);
decimal PrecoFilhoComIva = Convert.ToDecimal(dgv_Filho.CurrentRow.Cells["PrecoFilhoComIva"].Value);
if (dgv_Filho.Columns[e.ColumnIndex].Name == "PrecoFilhoSemIva")
{
PrecoFilhoComIva = PrecoFilho * (Iva / 100) + PrecoFilho;
dgv_Filho.CurrentRow.Cells["PrecoFilhoComIva"].Value = PrecoFilhoComIva;
}
else if (dgv_Filho.Columns[e.ColumnIndex].Name == "PrecoFilhoComIva")
{
decimal PrecoFilhoSemIva = PrecoFilhoComIva - (PrecoFilhoComIva / (1 + (Iva / 100)) * (Iva / 100));
dgv_Filho.CurrentRow.Cells["PrecoFilhoSemIva"].Value = PrecoFilhoSemIva;
}
Using this code, editing the preVAT value will automatically update the postVAT value accordingly, and editing the postVAT value will automatically update the preVAT value accordingly
Rather than interact with the DataGridView directly (which can be complex) you could instead make a class that implements INotifyPropertyChanged and keeps all of its internal calculations up-to-date at all times (which is easier). Here is a simplified version of such a class that responds to changes of Descricao, Medida and PrecoFilhoSemIva.
Simplified class that represents a row of data
class Articulo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
string _descricao = string.Empty;
public string Descricao
{
get => _descricao;
set
{
if (!Equals(_descricao, value))
{
_descricao = value;
OnPropertyChanged();
}
}
}
public string Descricao_Pai => $"{Descricao} {Medida_1}#{_precoFilhoSemIva.ToString("F2")}";
public decimal PrecoFilhoComIva => _precoFilhoSemIva * (1.0m + MainForm.Iva);
decimal _medida = 0;
public decimal Medida
{
get => _medida;
set
{
if (!Equals(_medida, value))
{
_medida = value;
OnPropertyChanged();
}
}
}
decimal _precoFilhoSemIva = 0;
public decimal PrecoFilhoSemIva
{
get => _precoFilhoSemIva;
set
{
if (!Equals(_precoFilhoSemIva, value))
{
_precoFilhoSemIva = value;
OnPropertyChanged();
}
}
}
string _codigoArtigo = System.Guid.NewGuid().ToString().Substring(0, 10).ToUpper();
public string CodigoArtigo
{
get => _codigoArtigo;
set
{
if (!Equals(_codigoArtigo, value))
{
_codigoArtigo = value;
OnPropertyChanged();
}
}
}
}
Instances of this class are placed in a BindingList which is assigned to the DataSource property of dgv_Filho and caused the DGV to update whenever the Refresh method is called.
Initializations
The only interaction that should be necessary with the DGV is to initialize the columns and bindings properly in the MainForm override for the Load event. This is also where we bind the combo box to a static value for Iva that can be used by the calculation for the row items.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
initDataGridView();
initComboBox();
}
private void initDataGridView()
{
dgv_Filho.DataSource = DataSource;
DataSource.ListChanged += (sender, e) =>
{
if (e.ListChangedType == ListChangedType.ItemChanged)
{
dgv_Filho.Refresh();
}
};
// Add one or more items to autogenerate the columns.
Random randomPriceGen = new Random(1);
for (int i = 1; i <= 3; i++)
{
var preco = i == 1 ? 1.0m : (decimal)randomPriceGen.NextDouble() * 100;
DataSource.Add(new Articulo
{
Descricao = $"Articulo {(char)('A' + (i - 1))}",
Medida = i,
PrecoFilhoSemIva = preco,
});
}
// Do a little column formatting
foreach (DataGridViewColumn column in dgv_Filho.Columns)
{
switch (column.Name)
{
case nameof(Articulo.Descricao):
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
column.MinimumWidth = 120;
break;
case nameof(Articulo.Medida):
case nameof(Articulo.PrecoFilhoSemIva):
case nameof(Articulo.PrecoFilhoComIva):
column.DefaultCellStyle.Format = "F2";
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
break;
default:
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
break;
}
}
}
private void initComboBox()
{
cb_Iva.SelectedIndex = 0;
cb_Iva.SelectedIndexChanged += onIvaSelected;
cb_Iva.KeyDown += (sender, e) =>
{
if( e.KeyData == Keys.Enter)
{
e.Handled = e.SuppressKeyPress = true;
}
onIvaSelected(sender, e);
};
onIvaSelected(cb_Iva, EventArgs.Empty);
void onIvaSelected(object sender, EventArgs e)
{
if (decimal.TryParse(cb_Iva.Text.Replace("%", string.Empty), out decimal iva))
{
Iva = iva / 100m;
dgv_Filho.Refresh();
cb_Iva.BackColor = SystemColors.Window;
}
else cb_Iva.BackColor = Color.LightSalmon;
}
}

Cannot add together different variables, even though values have changed

So I'm REALLY new to coding, so I'm learning as I go. I'm doing an assignment for a course, where I have to create a party booking program for a company. The idea is simple, just selected some different options, add them up, and calculate the costs. I have labels that will change and display the integer that the variable is set to, and they work perfectly which would tell me that the variables themselves are indeed getting changed.
However, once I try to add the variables together, it doesn't work.
public partial class AdultPayment : Form
{
public static int ConvertNumberAdult = Convert.ToInt32(Adult.numberAdult);
public static int MealCost = Adult.mealPrice*ConvertNumberAdult;
private static int PrivateRoomCost;
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
public static string DisplayNumberAdult = Convert.ToString(Adult.numberAdult);
private static int CalculateWine { get; set; } = ConvertNumberAdult / 6 * 15;
public AdultPayment()
{
InitializeComponent();
lblAdultConfirmName.Text = Adult.adultContactName;
lblAdultConfirmNumber.Text = Adult.adultContactNumber;
lblAdultConfirmDate.Text = Adult.adultDate;
lblAdultConfirmTime.Text = Adult.adultTime;
lblConfirmNumberOfAdult.Text = Adult.numberAdult.ToString();
lblMealCostTotal.Text = "£"+ MealCost.ToString();
lblCostTotal.Text = "£" + TotalCost.ToString();
if (Adult.adultPrivateRoom == true)
{
PrivateRoomCost = 40;
lblAdultConfirmPrivateRoom.Text = "Yes";
lblPrivateRoomTotal.Text = "£"+ PrivateRoomCost;
}
else
{
PrivateRoomCost = 0;
lblAdultConfirmPrivateRoom.Text = "No";
lblPrivateRoomTotal.Text = "N/A";
}
if(Adult.menuOption == true)
{
lblConfirmMenu.Text = "2 Courses for £15 each";
}
if(Adult.menuOption == false)
{
lblConfirmMenu.Text = "3 Courses for £18 each";
}
if (Adult.addWine == false)
{
CalculateWine = 0;
lblConfirmWineAdded.Text = "No";
lblWineTotal.Text = "N/A";
}
else
{
lblConfirmWineAdded.Text = "Yes";
lblWineTotal.Text = "£"+ CalculateWine.ToString();
}
lblCostTotal.Text = "£" + TotalCost.ToString();
}
}
I have a different form, that allows the users to select their preferences, which works just as I need it to.
The variable that is supposed to add the other variables together is
public static int TotalCost = MealCost + CalculateWine + PrivateRoomCost;
I genuinely am so confused now, and because I'm so new to this I don't know how else to word it in order to find anything on the internet
Any help would be great!
Thanks!

C# trouble in visual studio, can't get button click to execute lines properly

I am having some trouble with my code
The problem is every time I press the done button nothing calculates
I am using visual studio to code in C#
private void label1_Click(object sender, EventArgs e)
{
//Variable declaration
int Numtckets;
int NumberofULT = 35;
int NumberofSLT = 55;
int NumberofEZT = 42;
int Total = 0;
//Get input
Numtckets = int.Parse(Numberoftickesearned.Text);
//Processing
if (RADULT.Checked == true)
{
Total = NumberofULT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADSLT.Checked == true)
{
Total = NumberofSLT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADEZT.Checked == true)
{
Total = NumberofEZT * Numtckets;
TotalLbl.Text = "Your total is..." + Total;
}
else if (RADULT.Checked == false && RADSLT.Checked == false && RADEZT.Checked == false)
{
TotalLbl.Text = "Please enter the number of tickets" + Total;
}
}
}
}
I've tried editing the name properties and such with no luck. After I did that I still haven't gotten any results, any help would be appriecated.

How could I refactor this method in C#?

I have code which I need to refactor in order to use in many places. So I tried some solutions but always ending with repeated and messy code. So, I decided to ask what is possible best solutions.
This code is used for calculating sale price in e-commerce project. My goal is to put some code in method which will not change over time, or better to say, which will be managed only from one place. This part is considering of setting sale price based on some comparasion.
And problem occurs in this comparasion. I want also to do some formating of controls like Label based on this result, like setting currency code. The currency code will be sometimes in $, sometimes in USD. So, this mean I should somehow isolete this currency code also.
In short, I want to refactor this currency code and formating controls based on calculated sale price.
So, I created BasketHelper class with Product and Account properties and method SetBasketPayment that return properties I setted in this method. Basically, I use this approach to group properties of Product and Account classes and than return values.
Here is my code. Any further explanation, I will provide upon your request.
public class BasketHelper
{
public Product _product { get; set; }
public Account _account { get; set; }
public BasketHelper SetBasketPayment(Product product, Account account, HyperLink lblIconOnSale, Label lblSalePrice, Label lblListPrice, HyperLink lblIconCampaign)
{
decimal _brandAccountDiscountRate = default(decimal);
decimal _accountDiscount = default(decimal);
if (HttpContext.Current.Request.IsAuthenticated)
{
MembershipUser mUser = Membership.GetUser();
if (mUser != null)
{
account = Account.GetAccountByUserId((Guid)Membership.GetUser().ProviderUserKey);
try
{
_accountDiscount = account.DiscountRate;
}
catch (Exception ex) { }
BrandAccountDiscount brandAccountDiscount = BrandAccountDiscount.GetBrandAccountDiscountByUserAndBrandId(product.BrandId, mUser.ProviderUserKey.ToString());
if (brandAccountDiscount != null)
{
_brandAccountDiscountRate = brandAccountDiscount.DiscountRate;
}
}
}
decimal currencyMultiplier = Currency.GetCurrencyValue(product.CurrencyCode);
decimal _listPriceTL = product.ListPrice * currencyMultiplier;
decimal _productCampaignPrice = _listPriceTL * (1 - product.DiscountRate / 100);
decimal _accountPrice = _listPriceTL * (1 - _accountDiscount / 100);
decimal _brandPrice = _accountPrice * (1 - _brandAccountDiscountRate / 100);
lblListPrice.Text = product.ListPrice.ToString("N2") + " " + product.CurrencyCode;
if (product.DiscountRate > 0)
{
product.SalePrice = _productCampaignPrice;
lblSalePrice.Text = _productCampaignPrice.ToString("C2") + " + KDV";
lblListPrice.CssClass += " strike";
lblIconCampaign.Text = "+%" + product.DiscountRate.ToString("N0");
lblIconCampaign.Visible = true;
}
else
{
if (_accountPrice < _listPriceTL)
{
product.SalePrice = _accountPrice;
lblIconOnSale.Text = "%" + _accountDiscount.ToString();
lblIconOnSale.Visible = true;
}
if (_brandAccountDiscountRate > 0)
{
product.SalePrice = _brandPrice;
lblSalePrice.Text = _brandPrice.ToString("C2") + " +KDV";
}
}
return new BasketHelper
{
_product = product,
_account = account
};
}
}

Align in RichtextBox

Using this:
richTextBox1.AppendText("EMPID: " + "\t\t" + "4001");
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText("EmployeeName: " + "\t\t" + "Taborjakol");
I got this:
How I will perfectly Align it to this:
What you can do is change the tab positions of the RichTextBoxControl.
richTextBox1.SelectionTabs = new int[] { 90, 180, 270, 360 };
richTextBox1.AppendText("EMPID: " + "\t\t" + "4001");
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText(System.Environment.NewLine);
richTextBox1.AppendText("EmployeeName: " + "\t\t" + "Taborjakol");
The SelectionsTab property re-defines the spaces that are used for each tab in the RichTextBox control. You need to experiment with the tab settings to get the best result for your text.
Replace your last line of code with
richTextBox1.AppendText("EmployeeName: " + "\t" + "Taborjakol");
If you dont have to use a richtextbox, you should definetly have a look at the gridview or if you use third party tools like Telerik, DevCraft, ComponentOne and others most of them will have a control called Property Grid that has a layout you might be interested in.
If there is no other way around in using a richtextbox, you have to do the following:
Get a fixed-width font or called monospaced font http://en.wikipedia.org/wiki/Monospaced_font
Evalute the amout of characters which share the same width as a tab (I dont know the number of character have to figure it out yourself with testing)
Get the max length of your text at the left side (your "columnnames" I guess - like "EmployeeName")
Do some math - max length + one tab = x characters
now fill the remaining text at your left side with the neccessary tabs (can be anything from 1 to x) to get the same amout of characters as calculated in 4.
But again a richtextbox isnt the ideal control for this kind of scenario.
Edit:
Here some Code:
public partial class Form1 : Form
{
private const int FetchTestData = 50;
private const int TabCharLength = 5;
public Form1()
{
InitializeComponent();
//With this Fontsettings - 5 chars = 1 Tab - this changes with different fonts
this.richTextBox1.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
var type = typeof(TestData);
var list = GetTestData();
var maxProperty = GetMaxProperty(type);
maxProperty = FillToNext(maxProperty);
var properties = GetProperties(type);
for (var i = 0; i < FetchTestData; i++)
{
var data = list[i];
foreach (var propertyInfo in properties)
{
richTextBox1.AppendText(propertyInfo.Name);
var tabs = GetNumberOfTabs(maxProperty, propertyInfo.Name.Length);
for (var j = 0; j < tabs; j++)
richTextBox1.AppendText("\t");
richTextBox1.AppendText(Convert.ToString(propertyInfo.GetValue(data)));
richTextBox1.AppendText(Environment.NewLine);
}
if (i >= FetchTestData - 1)
continue;
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.AppendText("---------- NEXT DATA ----------");
richTextBox1.AppendText(Environment.NewLine);
}
}
private int GetNumberOfTabs(int maxLength, int textLength)
{
if ((maxLength % TabCharLength) != 0)
maxLength = FillToNext(maxLength);
var difLength = maxLength - textLength;
return (int)(Math.Floor(Convert.ToDouble(difLength / TabCharLength)) + 1);
}
private int FillToNext(int maxLength)
{
return maxLength + (5 - (maxLength % TabCharLength));
}
private PropertyInfo[] GetProperties(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
private int GetMaxProperty(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return (from x in GetProperties(type)
select x.Name.Length).Max();
}
private List<TestData> GetTestData()
{
var returnValue = new List<TestData>();
for (int i = 0; i < FetchTestData; i++)
{
returnValue.Add(new TestData()
{
ID = i,
Name = "NameValue " + i,
Description = "DescriptionValue " + i,
PropertyA = "PropertyAValue " + i,
PropertyB = "PropertyBValue " + i,
SomeReallyLongPropertyName = "RandomStuff... " + i
});
}
return returnValue;
}
}
public class TestData
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string SomeReallyLongPropertyName { get; set; }
}
As stated you firstly would want to set the font to a mono-space font, this means that each letter will be the same size.
So you will see something like this:
EEEEEEEEEEE
Rather than
EeEeeiiiiiiiiiiiiiiiiii
Secondly, you could align the text which may improve it slightly:
richTextBox1.SelectAll();
richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
However unless you have to, I would suggest using a different control:
Gridview
Listbox
These are both easy to format, gridview has tabs, and the listbox you can use string.Format when entering the values.

Categories

Resources