Change button background image using method in Winforms - c#

My code for Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace YAHTZEE
{
public partial class GameMainWindow : Form
{
public GameMainWindow()
{
InitializeComponent();
}
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
dm.intDice_1_Roll();
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
Class1 c1 = new Class1();
c1.buttonDice_1Manager();
}
}
}
My class for generating random number for all the dice.
This works perfectly fine.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace YAHTZEE
{
public class DiceManager
{
Random rnd = new Random();
public int intDice_1_Roll()
{
int intDice_1 = rnd.Next(1, 7);
return intDice_1;
}
public int intDice_2_Roll()
{
int intDice_2 = rnd.Next(1, 7);
return intDice_2;
}
public int intDice_3_Roll()
{
int intDice_3 = rnd.Next(1, 7);
return intDice_3;
}
public int intDice_4_Roll()
{
int intDice_4 = rnd.Next(1, 7);
return intDice_4;
}
public int intDice_5_Roll()
{
int intDice_5 = rnd.Next(1, 7);
return intDice_5;
}
}
}
Class to change button background image.
This is where my problem is, the code works if I put it on my form but it does nothing when I make it a method on another class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YAHTZEE.Properties;
namespace YAHTZEE
{
class Class1 : GameMainWindow
{
public void buttonDice_1Manager()
{
DiceManager dm = new DiceManager();
if (dm.intDice_1_Roll() == 1)
{
buttonDice_1.BackgroundImage = Properties.Resources.Dice1;
}
}
}
}
Am I missing something?
P.S. I want them to be separated because there are a lot of things to consider making my code very long.

In class1, try changing your method to:
public System.Drawing.Bitmap dice1Manager(int diceRoll)
{
if(diceRoll == 1)
return Properties.Resources.Dice1;
}
In your main class, change what you have to:
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
Class1 c1 = new Class1();
button_dice1.BackgroundImage = c1.dice1Manager(dm.intDice_1_Roll());
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
}

Related

Create an instance of a class from another package

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assign_5.model
{
class Person
{
public void t()
{
Console.WriteLine("try");
}
public string h()
{
return "ll";
}
}
}
using assign_5.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assign_5.Controller
{
class FirstNameController
{
Person p = new Person();
p.t();
string o = p.h();
}}
Why there is an error in p.t(); and string o = p.h();
"Error CS0236 A field initializer cannot reference the non-static field, method, or property 'FirstNameController.p' assign_5 "
You need move your code to a method in class, also make class Person as public to accessable from another namespace as
public class Person{}
class FirstNameController
{
void test(){
Person p = new Person();
p.t();
string o = p.h();
}
}

C# Ninject: How to inject dependency depending on field?

A class named Round is a level design in a adventure game.Its filed number indicate which level the player is in. Different level will have different figures to guess. The figures are produced by field FigureFactory.
The question is: using Ninject for dependency injection, how can I set the cooresponding FigureFactory to the variable round, according to the field number? For instance, when field number==1, the cooresponding factory is FigureFactory1, when field number==2, the cooresponding factory is FigureFactory2?
using GuessFigure.Model.Factory;
using Ninject;
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Planning.Bindings;
namespace GuessFigure.Model
{
class Round
{
private int number=1;
private FigureFactory figureFactory;
[Inject]
internal void SetFigureFactory(FigureFactory figureFactory)
{
this.figureFactory = figureFactory;
}
public int[] GetCurrentRoundFigures()
{
return figureFactory.Produce(number);
}
}
//this not work, help please
class RoundModule : NinjectModule
{
public override void Load()
{
Bind<FigureFactory>().To<FigureFactoryRound1>().When(request=>request.ParentRequest.Target.Type.GetField("number").Equals(1));
Bind<FigureFactory>().To<FigureFactoryRound2>().When(request => request.Target.Type.GetField("number").Equals(2));
Bind<FigureFactory>().To<FigureFactoryRound3>().When(request => request.Target.Type.GetField("number").Equals(3));
Bind<FigureFactory>().To<FigureFactoryRound4>().When(request => request.Target.Type.GetField("number").Equals(4));
Bind<FigureFactory>().To<FigureFactoryRound5>().When(request => request.Target.Type.GetField("number").Equals(5));
}
}
}
Factory Method Pattern implementation:
using System;
namespace GuessFigure.Model
{
abstract class FigureFactory
{
protected int figureNumber;
public FigureFactory(int figureNumber)
{
this.figureNumber = figureNumber;
}
internal int[] Produce()
{
int[] figureArray = new int[figureNumber];
for (int i = 0; i < figureNumber; i++)
{
figureArray[i] = Algorithm(i + 1);
}
return figureArray;
}
abstract protected int Algorithm(int inputNumber);
}
}
Concrete Factory(there are still some like this);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model
{
class FigureFactoryRound1 : FigureFactory
{
public FigureFactoryRound1(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return inputNumber;
}
}
}
class FigureFactoryRound3 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model.Factory
{
class FigureFactoryRound3 : FigureFactory
{
public FigureFactoryRound3(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return (int) Math.Pow( inputNumber,2) ;
}
}
}
class FigureFactoryRound4 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessFigure.Model.Factory
{
class FigureFactoryRound4 : FigureFactory
{
public FigureFactoryRound4(int figureNumber) : base(figureNumber)
{
}
protected override int Algorithm(int inputNumber)
{
return (int)Math.Pow(inputNumber, 3);
}
}
}
Usage:
IKernel kernel = new StandardKernel(new RoundModule());
Round round = new Model.Round();
round.SetFigureFactory(kernel.Get<FigureFactory>());
int[] array=round.GetCurrentRoundFigures();

Exception Handling in a Windows Forms Application

I'm doing a program for serial communications. To centralize the process of access to serial, created a class.
I am having problem when an exception is lançanda within the class leaves the locked program.
example:
When trying aberir the serial port, can give error and the system is at that point to burst memory.
How should I handle errors?
Put try and catch?
Add another routine?
Error point:
portSerial.Open();
Program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PortSerial.Lib;
namespace ProgramPortSerial
{
public partial class Form1 : Form {
public static LibPortaSerial portSerial = new LibPortSerial();
public Form1()
{
InitializeComponent();
portSerial.LineReceived += new LineReceivedEventHandler(sp1_LineReceived);
portSerial.Init(
ref cmbPortas,
ref cmbVelocidade,
ref cmbBitsDeDados,
ref cmbPariedade,
ref cmbBitsDeParada,
ref cmbControleDeFluxo);
}
void sp1_LineReceived(object sender, LineReceivedEventArgs Args)
{
// Tem que ser em uma nova thread para não travar
Invoke(new Action(() =>
{
memDadosRecebidos.Text += "\r\n" + Args.Resposta;
}));
}
private void btnAbrirPorta_Click(object sender, EventArgs e)
{
portSerial.Open();
}
}
}
Class PortSerial
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace PortSerial.Lib
{
public class LibPortSerial : IDisposable
{
public SerialPort portSerial;
public LibPortSerial()
{
portSerial = new SerialPort();
}
public void Dispose()
{
if (portSerial != null)
portSerial.Dispose();
}
public void Open(
string port,
int veloc,
int bitsData,
string pariedade,
string bitsStop,
string control)
{
portSerial.PortName = port;
portSerial.BaudRate = veloc;
portSerial.DataBits = bitsData;
portSerial.Parity = SetPariedade(pariedade);
portSerial.StopBits = SetBitsStop(bitsStop);
portSerial.Handshake = Setcontrol(control);
portSerial.Open(); // ==> Erro this point
}
}
}
You should write it as:
public void Open(
string port,
int veloc,
int bitsData,
string pariedade,
string bitsStop,
string control)
{
portSerial.PortName = port;
portSerial.BaudRate = veloc;
portSerial.DataBits = bitsData;
portSerial.Parity = SetPariedade(pariedade);
portSerial.StopBits = SetBitsStop(bitsStop);
portSerial.Handshake = Setcontrol(control);
try
{
portSerial.Open(); // ==> Erro this point
}
catch(IOException exp)
{
return exp.Message;
}
}

Current Context error

I am having trouble calling out Method Globals.Global.InstantiateBlowerObj(); in public frmMain(). I am getting the error "The name 'Globals.Global.InstantiateBlowerObj' does not exist in the current context." I have all the classes and methods as public and I cant figure this out.
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;
using WetVacClient;
using Globals;
using Globals.Global;
namespace Globals
{
public class Global
{
public Blower[] _Blower = new Blower[4];
public void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}
}
}
namespace WetVacClient
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
Globals.Global.InstantiateBlowerObj();
}
}
}
You need to make both the method and _Blower Property Static
public static Blower[] _Blower = new Blower[4];
public static void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}
Otherwise create an intance of Global and call it's instance method (but that's not what you want I think).
Globals.Global g=new Globals.Global();
g.InstantiateBlowerObj();
Make it static.
You are trying to access a non-static member in an static context.
public static void InstantiateBlowerObj()
{
for (int i = 1; i < 4; i++)
_Blower[i] = new Blower(i);
}

Noob Concern: Assigning a value to variable from new class object. C#

DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
I am creating a new object of the DinnerFun class and trying to assign the value from the numeric up down object from the form to the int variable PeepQty.
When I go into debug mode, I can see that sure enough nudPeepQty has a numeric value, but it is never assigned to PeepQty, and my ending calculation always ends as 0.
As the problem might be something related to something I've done outside this line of code, I will add the rest of my project below:
DinnerParty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MonuEventPlanning
{
class DinnerFun
{
const int FoodCost = 25;
public int PeepQty;
decimal CostOfBeverage;
decimal CostOfDecorations;
decimal TotalCost;
public void CalcDrinks(bool HealthOption)
{
if (HealthOption)
{
CostOfBeverage = 5M;
}
else
{
CostOfBeverage = 20M;
}
}
public void CalcDecorations(bool FancyOption)
{
if (FancyOption)
{
CostOfDecorations = (PeepQty * 15M) + 50M;
}
else
{
CostOfDecorations = (PeepQty * 7.5M) + 30M;
}
}
public decimal CalcTotalCost(bool HealthyOption)
{
if (HealthyOption)
{
TotalCost = (CostOfDecorations + CostOfBeverage) * .95M;
return TotalCost;
}
else
{
TotalCost = (CostOfBeverage + CostOfDecorations) + (PeepQty*25M);
return TotalCost;
}
}
}
}
------------Form1.cs -------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MonuEventPlanning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost();
}
public void DisplayCost()
{
DinnerFun dinnerFun = new DinnerFun();
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}
}
}
The issue is that you are creating another DinnerFun that is not the same as the first one. Naturally the DinnerFun object in DisplayCost will have zero for the property value. Perhaps you meant this...
private void btnCalc_Click(object sender, EventArgs e)
{
DinnerFun dinnerFun = new DinnerFun { PeepQty = (int)nudPeepQty.Value };
dinnerFun.CalcDrinks(cbxHealthy.Checked);
dinnerFun.CalcDrinks(cbxFancy.Checked);
DisplayCost(dinnerFun);
}
public void DisplayCost(DinnerFun dinnerFun)
{
tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString("c");
}

Categories

Resources