Is there any to shorten the code that needs variables? - c#

I've always wondered, are there ways to shorten this kind of code?
private void Update01()
{
item01.text = item01n + "\nCost: " + Math.Round(cost01, 2) + "\nYou have: " + n01;
}
private void Update02()
{
item02.text = item02n + "\nCost: " + Math.Round(cost02, 2) + "\nYou have: " + n02;
}
private void Update03()
{
item03.text = item03n + "\nCost: " + Math.Round(cost03, 2) + "\nYou have: " + n03;
}
.
.
.
Thanks for the help.

As 12seconds said, just return a string and pass in 3 variables:
private string GetUpdate(item, cost, n)
{
return item + "\nCost: " + Math.Round(cost, 2) + "\nYou have: " + n;
}
And then simply do:
item01.text = GetUpdate(item01n, cost01, n01);
item02.text = GetUpdate(item02n, cost02, n02);
item03.text = GetUpdate(item03n, cost03, n03);

Related

Data from List<Memo> doesn't show in datagridview

I have a list made by user input which is bound to a datasource class, I also have a datagridview where the data is supposed to be put into the datagrid.
private void ViewMemo_Load(object sender, EventArgs e)
{
dgvMemo.DataSource = Datasources.memorecorders;
}
this is the AddMemo class
private void btAdd_Click(object sender, EventArgs e)
{
int SerialId;
SerialId = int.Parse(txtSerialId.Text);
decimal price;
price = decimal.Parse(txtPrijs.Text);
MemoRecorder m1 = new MemoRecorder(SerialId);
m1.make = txtMerk.Text;
m1.model = txtModel.Text;
m1.priceExBtw = price;
m1.creationDate = dtProductie.Value;
foreach (MemoCartridgeType mem in Enum.GetValues(typeof(MemoCartridgeType)))
{
if (cbCartridge.SelectedValue.ToString() == mem.ToString())
{
m1.maxCartridgeType = mem;
}
}
Datasources.memorecorders.Add(m1);
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
txtMerk.Text = String.Empty;
txtModel.Text = String.Empty;
txtPrijs.Text = String.Empty;
}
but when I view the datagridview the data is not in there, what did I do wrong?
Datasources.memorecorders.Add(m1);
dgvMemo.DataSource = Datasources.memorecorders;
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);

Input string was not in the correct format with Entity Framework

I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.

C# two message boxes popping up - need to stop one

Both message boxes run after each other when no buttons are checked when only the following should show:
{ MessageBox.Show("Incomplete order. Please review.", "Incomplete Order."); }
How do I prevent the following messagebox from running when no buttons are checked?
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
"Code"
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}
You will go a long way if you changed
if (SmallPizza.Checked)
to
else if (SmallPizza.Checked)
You can exit the function after the first error message appears. just place a return; after the messagebox
Slight variation to the else if suggestions by Frank Pytel. Rather than changing subsequent if's to else if's it needs to be an if else for the first validation check then the series of if statements within the else block as follows..
private void ConfirmOrder_Click(object sender, EventArgs e)
{
string pizzaChoice = "";
if (NeapolitanStyle.Checked == false & NEGreekStyle.Checked == false & ChicagoStyle.Checked == false & SmallPizza.Checked == false & MediumPizza.Checked == false & LargePizza.Checked == false)
{
MessageBox.Show("Incomplete order. Please review.", "Incomplete Order.");
}
else {
if (SmallPizza.Checked)
{
pizzaChoice = pizzaChoice + SmallPizza.Text + " ";
}
if (MediumPizza.Checked)
{
pizzaChoice = pizzaChoice + MediumPizza.Text + " ";
}
if (LargePizza.Checked)
{
pizzaChoice = pizzaChoice + LargePizza.Text + " ";
}
if (NEGreekStyle.Checked)
{
pizzaChoice = pizzaChoice + NEGreekStyle.Text + " pizza" + "\n";
}
if (ChicagoStyle.Checked)
{
pizzaChoice = pizzaChoice + ChicagoStyle.Text + " pizza" + "\n";
}
if (NeapolitanStyle.Checked)
{
pizzaChoice = pizzaChoice + NeapolitanStyle.Text + " pizza" + "\n";
}
if (VeryHotChilis.Checked)
{
pizzaChoice = pizzaChoice + "& " + VeryHotChilis.Text + "." + "\n";
}
if (Onions.Checked)
{
pizzaChoice = pizzaChoice + "& " + Onions.Text + "." + "\n";
}
if (Mushrooms.Checked)
{
pizzaChoice = pizzaChoice + "& " + Mushrooms.Text + "." + "\n";
}
MessageBox.Show("You have ordered a " + pizzaChoice, "Order Confirmation.");
}
}
You also can do like
if (MessageBox.Show("First MessageBox", "Test", MessageBoxButtons.OK) == System.Windows.Forms.DialogResult.OK) {
MessageBox.Show("Second messageBox", "Test", MessageBoxButtons.OK);
}
Okay entering return; did the trick. I tried putting the 'else if' in but both message boxes were still popping up.
Thanks guys. Most appreciated.

How do I fill a text box using a public string?

I have this frustrating problem that I can't seem to solve.
I try to fill a TextBox with text from a public static string.
But when I run the program it just shows a blank text box with nothing in it.
I don't have any errors so it's hard for me to understand what I'm doing wrong.
Here is the code I have:
public ShowMp3()
{
InitializeComponent();
OverzichttxtBox.Text = OverzichtMP3();
}
public static String OverzichtMP3()
{
String overzicht = "";
foreach (Mp3Player player in Mp3.GetPlayers())
overzicht = overzicht + "ID: " + Convert.ToString(player.id) + "\r\n" +
"Merk: " + player.make + "\r\n" + "Model: " + player.model +
"\r\n" + "MB-size: " + player.mBSize + "\r\n" + "Prijs: " +
player.price + "\r\n" + "\r\n";
return overzicht;
}
And Mp3.GetPlayers() is this:
private static ArrayList players = new ArrayList();
public static void Initialize()
{
Mp3Player player1 = new Mp3Player(1, "GET Technologies .inc", "HF 410", 4096, 129.95M, 500);
Mp3Player player2 = new Mp3Player(2, "Far & Loud", "XM 600", 8192, 224.95M, 500);
Mp3Player player3 = new Mp3Player(3, "Innotivative ", "Z3", 512, 79.95M, 500);
Mp3Player player4 = new Mp3Player(4, "Resistance S.A.", "3001", 4096, 124.95M, 500);
Mp3Player player5 = new Mp3Player(5, "CBA", "NXT Volume", 2048, 159.05M, 500);
players.Add(player1);
players.Add(player2);
players.Add(player3);
players.Add(player4);
players.Add(player5);
}
public static ArrayList GetPlayers()
{
return players;
}
I suspect the problem is you're never calling Mp3.Initialize(). You could add this to a static constructor in the Mp3 class:
private static List<Mp3Player> players = new List<Mp3Player>();
static Mp3()
{
Initialize();
}
// This can be private now...
private static void Initialize()
{
....
Note that you may want to change the ArrayList to a List<Mp3Player>, as well.
Also, as an aside, you should give StringBuilder and String.Format a try. Instead of this...
overzicht = overzicht + "ID: " + Convert.ToString(player.id) + "\r\n" +
"Merk: " + player.make + "\r\n" + "Model: " + player.model +
"\r\n" + "MB-size: " + player.mBSize + "\r\n" + "Prijs: " +
player.price + "\r\n" + "\r\n";
You can do:
StringBuilder overzicht = new StringBuilder();
overzicht.AppendLine(String.Format("ID: {0}", player.id));
overzicht.AppendLine(String.Format("Merk: {0}", player.make));
overzicht.AppendLine(String.Format("Model: {0}", player.model));
overzicht.AppendLine(String.Format("MB-size: {0}", player.mBSize));
overzicht.AppendLine(String.Format("Prijs: {0}", player.price));
return overzicht.ToString();
Much easier to read ;)
My String.Format isn't that compelling here... but if this was all on one line, it'd be much more useful:
return String.Format("ID:{0}, Merk:{1}, Model:{2}, MB-size:{3}, Prijs:{4}",
player.id, player.make, player.mode,
player.mBSize, player.price);

make if statements look better

How can I make this look better:
lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb"; // Total world size
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem)) // World itself
{
lblWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem) * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether")) // Nether
{
lblNetherSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether") * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end")) // The End
{
lblTheEndSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end") * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
It really looks like a mess and I can't seem to find any questions like this.
Well, there are several things that can help here:
A helper method (you're performing the same conversion from "path" to "size string" each time)
The conditional operator
Extracting a common local variable
Something like this:
// Note that _worldsDirectory must be an absolute path)
string prefix = Path.Combine(_worldsDirectory, selectedItem, selectedItem);
lblWorldSize.Text = GetDirectorySizeOrDefault(prefix, "Couldn't find world");
lblNetherSize.Text = GetDirectorySizeOrDefault(prefix + "_nether",
"Couldn't find _nether");
lblTheEndSize.Text = GetDirectorySizeOrDefault(prefix + "_the_end",
"Couldn't find _the_end");
...
static string GetDirectorySizeOrDefault(string directory, string defaultText)
{
return Directory.Exists(directory)
? GetDirectorySize(directory) * 1024 + " kb"
: defaultText;
}
Note that I've corrected the fact that your original code always assigns to lblWorldSize.Text on error - I assume that wasn't deliberate.
Please use Path.Combine for path creation, and not string concatenation like you do.
Is it possible that this method does more than 1 things? You could refactor this in a few other methods maybe.
I would suggest to use intention and variable substitution to enhance readability:
string dir = "_worldsDirectory + selectedItem";
string dirItemPath = #"_worldsDirectory + selectedItem \\" + selectedItem;
// Total World Size
lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb";
// World itself
if (Directory.Exists(dirItemPath)) {
lblWorldSize.Text = GetDirectorySize(dirItemPath) * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}
// Nether
if (Directory.Exists(dirItemPath + "_nether")) {
lblNetherSize.Text = GetDirectorySize(dirItemPath + "_nether") * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}
// The End
if (Directory.Exists(dirItemPath + "_the_end")) {
lblTheEndSize.Text = GetDirectorySize(dirItemPath + "_the_end") * 1024 + " kb";
} else {
lblWorldSize.Text = "Couldn't find world.";
}
lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb"; // Total world size
DoOnDirectoryExists(lblWorldSize, "");
DoOnDirectoryExists(lblNetherSize, "_nether");
DoOnDirectoryExists(lblWorldSize, "_the_end");
//Change the name to something more appropriate to your program, same with the LBL type and tempString
public bool DoOnDirectoryExists(LBL lbl, string suffix)
{
string tempString = _worldsDirectory + selectedItem + "\\" + selectedItem + suffix;
if (Directory.Exists(tempString))
{
lbl.Text = GetDirectorySize(tempString) * 1024 + " kb";
}
else
{
lblWorldSize.Text = "Couldn't find world.";
}
}
Best way to get rid of clutter and make your code more readable - remove code duplication.

Categories

Resources