` private void getbtn_Click(object sender, EventArgs e) // To generate Images
{
if (cmbDocType.SelectedIndex > 0)
{
if (con.State != ConnectionState.Open)
con.Open();
string directory = System.IO.Directory.GetDirectoryRoot(System.IO.Directory.GetCurrentDirectory().ToString());
string FileNamePath = directory + "MembersDocuments\\" + GlobalValues.Member_ID + "\\" + cmbDocType.Text;
string[] list = Directory.GetFiles(FileNamePath);
if (list.Length > 0)
{
label1.Text = "";
PictureBox[] picturebox = new PictureBox[list.Length];
int y = 0;
for (int index = 0; index < picturebox.Length; index++)
{
picturebox[index] = new PictureBox();
if (x % 3 == 0)
{
y = y + 150; // 3 images per rows, first image will be at (20,150)
x = 0;
}
picturebox[index].Location = new Point(x * 230 + 20, y);
picturebox[index].Size = new Size(200, 150);
x++;
picturebox[index].Size = new Size(200, 100);
picturebox[index].Image = Image.FromFile(list[index]);
picturebox[index].SizeMode = PictureBoxSizeMode.StretchImage;
picturebox[index].Click += new EventHandler(picturebox_Click);
cmbDocType_SelectedIndexChanged(picturebox[index], e);
this.Controls.Add(picturebox[index]);
}
}
else
{
label1.Text = "No Images to display";
label1.ForeColor = Color.Red;
}
con.Close();
}
else
{
MessageBox.Show("Please select the Document Type");
}
}
`
Can anyone tell me how to clear previous images(result of first call) in dynamically created pictureboxes on a new call. On making new call,previous images should not be seen..in c#
I have combobox named Type.
lets say if i have Aminals,Birds in my Combobox.
on first call pictures of animals will be displayed and on choosing combobox for second time i.e birds, Pictures of Both the types are getting displayed.
i Need to display Pictures of single type at a time. in c#
Thanks;
As suggested by TaW in the comments:
private List<PictureBox> PBs = new List<PictureBox>();
private void getbtn_Click(object sender, EventArgs e) // To generate Images
{
if (cmbDocType.SelectedIndex > 0)
{
foreach(PictureBox pb in PBs)
{
pb.Dispose();
}
PBs.Clear();
if (con.State != ConnectionState.Open)
con.Open();
string directory = System.IO.Directory.GetDirectoryRoot(System.IO.Directory.GetCurrentDirectory().ToString());
string FileNamePath = directory + "MembersDocuments\\" + GlobalValues.Member_ID + "\\" + cmbDocType.Text;
string[] list = Directory.GetFiles(FileNamePath);
if (list.Length > 0)
{
label1.Text = "";
PictureBox PB;
int y = 0;
for (int index = 0; index < list.Length; index++)
{
PB = new PictureBox();
if (x % 3 == 0)
{
y = y + 150; // 3 images per rows, first image will be at (20,150)
x = 0;
}
PB.Location = new Point(x * 230 + 20, y);
PB.Size = new Size(200, 150);
x++;
PB.Size = new Size(200, 100);
PB.Image = Image.FromFile(list[index]);
PB.SizeMode = PictureBoxSizeMode.StretchImage;
PB.Click += new EventHandler(picturebox_Click);
PBs.Add(PB);
this.Controls.Add(PB)
cmbDocType_SelectedIndexChanged(PB, e);
}
}
else
{
label1.Text = "No Images to display";
label1.ForeColor = Color.Red;
}
con.Close();
}
else
{
MessageBox.Show("Please select the Document Type");
}
}
Related
I want to generate and change the image in the PictureBox array by button click.
Here is what I have tried so far.
public Form1() {
InitializeComponent();
}
PictureBox[] boxes = new PictureBox[6];
private void GenerateButton1_Click(object sender, EventArgs e) {
for (int i = 0; i < boxes.Length; i++) {
boxes[i] = new PictureBox(); //set the pointer to a new PictureBox instance
if (i == 0) boxes[i].Location = new System.Drawing.Point(3, 3);
if (i == 1) boxes[i].Location = new System.Drawing.Point(221, 3);
if (i == 2) boxes[i].Location = new System.Drawing.Point(439, 3);
if (i == 3) boxes[i].Location = new System.Drawing.Point(3, 210);
if (i == 4) boxes[i].Location = new System.Drawing.Point(221, 210);
if (i == 5) boxes[i].Location = new System.Drawing.Point(439, 210);
boxes[i].Size = new System.Drawing.Size(200, 200);
boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG"); //for setting its image
}
this.Controls.AddRange(boxes);
}
private void button1_Click(object sender, EventArgs e) {
int i = 3;
int signal = 1;
boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;
if (signal == 0) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\red.PNG");
if (signal == 1) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\green.PNG");
if (signal == 2) boxes[i].Image = Image.FromFile(Application.StartupPath + "\\grey.PNG");
}
}
}
by doing button1 click, the image will change from red.PNG to green.PNG or grey.PNG depending on the condition, however, I have to redo the image Properties declaration, for example, boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;. Otherwise the PictureBox lose its properties.
Is there any simpler way to do this.
Thank you in advance.
I want to have list of PictureBox inside the FlowLayoutPanel.These Picture box with images are added dynamically at run time. Now the problem I have got is, I have to add more than picturebox to panel and when I do that the picture box at the end seems to be missing though it seems like the space for those images are allocated.So how can I overcome this problem.
panel1.Controls.Clear();
Point NewLocation = new System.Drawing.Point(0, 0);
int CurrentImgIndex = 0;
foreach (ScannedImages image in Global.ScannedReportList[0].ImageCollection)
{
panel1.SuspendLayout();
PictureBox pbTemp = new PictureBox();
pbTemp.BackColor = System.Drawing.Color.Transparent;
pbTemp.Location = NewLocation;
pbTemp.Name = "picImage";
pbTemp.Size = new System.Drawing.Size(757*2, 980*2);
pbTemp.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
pbTemp.TabIndex = 7;
pbTemp.TabStop = false;
pbTemp.Tag = CurrentImgIndex + 1;
pbTemp.DragDrop += new System.Windows.Forms.DragEventHandler(this.PbTemp_DragDrop);
pbTemp.DragOver += new System.Windows.Forms.DragEventHandler(this.PbTemp_DragOver);
pbTemp.Click += new EventHandler(this.pbTemp_Click);
try
{
//pm
Image img = Global.ScannedReportList[0].ImageCollection[CurrentImgIndex].GetImageObject();
txtCurrentPage.Text = (CurrentImageIndex + 1).ToString();
//pm image
RotateAngle = Global.ScannedReportList[0].ImageCollection[CurrentImgIndex].RotationAngle;
//drpGroupTool.SelectedIndex = Global.ScannedReportList[0].ImageCollection[CurrentImgIndex].DocumentGroup;
switch (RotateAngle)
{
case 90:
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 180:
img.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 270:
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
}
//pm
m_szOriginal = img.Size;
pbTemp.Image = img;
if (Brightness != 0)
pbTemp.Image = AdjustBrightness(new Bitmap(pbTemp.Image), Brightness);
if (Contrast != 0)
pbTemp.Image = AdjustContrast1(new Bitmap(pbTemp.Image), Contrast);
panel1.Controls.Add(pbTemp);
panel1.ResumeLayout();
this.panel1.PerformLayout();
this.panel1.Refresh();
//pm
if (RotateAngle == 90 || RotateAngle == 270)
{
NewLocation.Y += img.Width;
}
else if (RotateAngle == 0 || RotateAngle == 180)
{
NewLocation.Y += img.Height;
}
//
CurrentImgIndex++;
this.Refresh();
index[CurrentImgIndex] = CurrentImgIndex + 1;
}
catch
{
pbTemp.Image = null;
}
I need help with the Check button. After a user adds all the 42 numbers in the textbox and enter a number from 0-9 in the "Enter number" area and clicks on the start button, next what he should do is run through the array of labels with the red label or lblCovece and he should collect the same values like the number enters before. And after he clicks on the Check button, the programme should first validate if the value that is selected with the red label is the same as the number entered. If is valid the label should turn green and than the result should appear in the label lblResultE(the result for example should be like this: if the number entered is 2, the result it is 2+2+2...)and if is not valid in the lblResultE we take out 10 points. That's what i did by now with some help.:) thank you.
namespace Seminarska
{
public partial class Form1 : Form
{
private Label l,l2,lblCovece,l4,lblResultE;
private Button bUp, bRight, bLeft, bDown, bCheck,bStart, bReset;
private TextBox txtVnes, txtGoal;
private Label[] pole;
public Form1()
{
InitializeComponent();
l2 = new Label();
l2.Text = " Enter one number";
l2.Location = new Point(230, 200);
l2.AutoSize = true;
l4 = new Label();
l4.Text = "Score";
l4.Location = new Point(240, 260);
l4.AutoSize = true;
lblResultE = new Label();
lblResultE.Location = new Point(350, 260);
lblResultE.AutoSize = true;
bLeft = new Button();
bLeft.Location = new Point(0, 250);
bLeft.Width=75;
bLeft.Height = 25;
bLeft.Text = "LEFT";
bCheck = new Button();
bCheck.Location = new Point(75, 250);
bCheck.Width = 75;
bCheck.Height = 25;
bCheck.Text = "Check";
bRight = new Button();
bRight.Location = new Point(150, 250);
bRight.Width = 75;
bRight.Height = 25;
bRight.Text = "RIGHT";
bUp = new Button();
bUp.Location = new Point(75, 220);
bUp.Width = 75;
bUp.Height = 25;
bUp.Text = "UP";
bDown = new Button();
bDown.Location = new Point(75, 280);
bDown.Width = 75;
bDown.Height = 25;
bDown.Text = "DOWN";
bStart = new Button();
bStart.Location = new Point(240, 165);
bStart.Width = 75;
bStart.Height = 25;
bStart.Text = "START";
bReset = new Button();
bReset.Location = new Point(320, 165);
bReset.Width = 75;
bReset.Height = 25;
bReset.Text = "RESET";
txtVnes = new TextBox();
txtVnes.Location = new Point(240, 10);
txtVnes.Width = 160;
txtVnes.Height = 130;
txtVnes.Multiline = true;
txtGoal = new TextBox();
txtGoal.Width = 75;
txtGoal.Height = 25;
txtGoal.Location = new Point(330, 200);
lblCovece = new Label();
lblCovece.Location = new Point(160,165);
lblCovece.Width = 20;
lblCovece.Height = 20;
lblCovece.TextAlign = ContentAlignment.MiddleCenter;
lblCovece.Text = "O";
lblCovece.BackColor = Color.FromArgb(255, 0, 0);
int a = 0;
pole = new Label[42];
this.Controls.Add(lblCovece);
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 7; j++)
{
l = new Label();
l.Name = "label" + i.ToString() + j.ToString();
l.Text = "Z";
l.Width = 20;
l.Height = 20;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Parent = this;
l.BackColor = Color.FromArgb(100, 149, 237);
l.Location = new Point(10 + (j - 1) * 25, 15 + (i - 1) * 25);
pole[a] = l;
this.Controls.Add(l);
a++;
}
}
this.Width = 460;
this.Height = 380;
this.Controls.Add(l2);
this.Controls.Add(l4);
this.Controls.Add(lblResultE);
this.Controls.Add(lblTimeE);
this.Controls.Add(bStart);
this.Controls.Add(bReset);
this.Controls.Add(txtGoal);
this.Controls.Add(txtVnes);
this.Controls.Add(bUp);
this.Controls.Add(bLeft);
this.Controls.Add(bRight);
this.Controls.Add(bDown);
this.Controls.Add(bCheck);
bStart.Click+=new EventHandler(bStart_Click);
bUp.Click+=new EventHandler(bUp_Click);
bDown.Click+=new EventHandler(bDown_Click);
bLeft.Click+=new EventHandler(bLeft_Click);
bRight.Click+=new EventHandler(bRight_Click);
bCheck.Click+=new EventHandler(bZemaj_Click);
bReset.Click+=new EventHandler(bReset_Click);
}
private void bStart_Click(object sender, EventArgs e)
{
string Str = txtGoal.Text.Trim();
int Num;
bool isNum = int.TryParse(Str, out Num);
if (isNum && Str.Length == 1)
{
string[] ts = txtVnes.Text.Split(
new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
int row = 0;
for (int i = 0; i < ts.Length && row < 6; i++)
{
if (LineIsValid(ts[i]))
{
for (int col = 0; col < 7; col++)
{
pole[row * 7 + col].Text = ts[i][2 * col].ToString();
}
row++;
}
}
for (; row < 6; row++)
{
for (int col = 0; col < 7; col++)
{
pole[row * 7 + col].Text = "Z";
}
}
}
else
{
MessageBox.Show("Invalid Input");
}
}
private static Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
private static bool LineIsValid(string line)
{
return regex.IsMatch(line);
}
private void bReset_Click(object sender, EventArgs e)
{
txtVnes.Clear();
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
int row = 0;
for (int i = 0; i < ts.Length && row < 6; i++)
{
for (int col = 0; col < 7; col++)
{
pole[row * 7 + col].Text = "Z";
pole[row * 7 + col].BackColor=Color.FromArgb(100, 149, 237);
}
row++;
}
for (; row < 6; row++)
{
for (int col = 0; col < 7; col++)
{
pole[row * 7 + col].Text = "Z";
pole[row * 7 + col].BackColor = Color.FromArgb(100, 149, 237);
}
}
txtGoal.Clear();
lblCovece.Location=new Point(160,165);
}
private void bUp_Click(object sender, EventArgs e)
{
lblCovece.Location = new Point(lblCovece.Location.X, lblCovece.Location.Y -
25);
}
private void bDown_Click(object sender, EventArgs e)
{
lblCovece.Location = new Point(lblCovece.Location.X, lblCovece.Location.Y +
25);
}
private void bLeft_Click(object sender, EventArgs e)
{
lblCovece.Location = new Point(lblCovece.Location.X - 25,
lblCovece.Location.Y);
}
private void bRight_Click(object sender, EventArgs e)
{
lblCovece.Location = new Point(lblCovece.Location.X + 25,
lblCovece.Location.Y);
}
private void bCheck_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
What makes your programm complicated and difficult to understand, is that you mix game logic with display logic.
I suggest you to redesign your game. It could look something like this:
public enum State
{
Empty, // Displays "Z"
Neutral, // Blue
Good, // Green
Bad // Red
}
public class Square
{
public int Number { get; set; }
public State State { get; set; }
}
public class Game
{
public const int Width = 7, Height = 6;
public Game()
{
Board = new Square[Width, Height];
}
public event EventHandler GameChanged;
public Square[,] Board { get; private set; }
public int CurrentX { get; private set; }
public int CurrentY { get; private set; }
public void Reset()
{
for (int x = 0; x < Width; x++) {
for (int y = 0; y < Height; y++) {
Board[x, y].State = State.Empty; // Always displayed in blue as "Z"
}
}
OnGameChanged();
}
public void MoveLeft()
{
if (CurrentX > 0) {
CurrentX--;
OnGameChanged();
}
}
public void MoveRight()
{
if (CurrentX < Width - 1) {
CurrentX++;
OnGameChanged();
}
}
// and so on
private void OnGameChanged()
{
EventHandler eh = GameChanged;
if (eh != null) {
eh(this, EventArgs.Empty);
}
}
}
In the form I would define pole to be a matrix as well (like the board). I show only a few relevant parts of the form code, to give you an idea of what I mean:
public class Form1 : Form
{
private Game game;
private Label[,] pole;
public Form1()
{
game = new Game();
game.GameChanged += new EventHandler(Game_GameChanged);
pole = new Label[Game.Width, Game.Height];
// Intialize pole.
// ...
}
void Game_GameChanged(object sender, EventArgs e)
{
for (int x = 0; x < Game.Width; x++) {
for (int y = 0; y < Game.Height; y++) {
Square square = game.Board[x, y];
Label label = pole[x,y];
switch (square.State) {
case State.Empty:
label.BackColor = Color.Blue;
label.Text = "Z";
break;
case State.Neutral:
label.BackColor = Color.Blue;
label.Text = square.Number.ToString();
break;
case State.Good:
label.BackColor = Color.Green;
label.Text = square.Number.ToString();
break;
case State.Bad:
label.BackColor = Color.Red;
label.Text = square.Number.ToString();
break;
default:
break;
}
}
}
// Place lblCovece according to game.CurrentX and game.CurrentY
// ...
}
private void bReset_Click(object sender, EventArgs e)
{
game.Reset();
}
private void bLeft_Click(object sender, EventArgs e)
{
game.MoveLeft();
}
private void bRight_Click(object sender, EventArgs e)
{
game.MoveRight();
}
}
Note how the Game class tells the form when changes happen through the event GameChanged. The form then updates the game display. In the game class, you can now concentrate on the game logic and do not have to deal with buttons and labels. You can also work with logical coordinates in the range [0..6] and [0..5] of the game board. This is easier than working with pixels. You delegate all the pixel calculations to the form.
My example is not complete, but when you try to implement it, you will see that it will be much easier to think about how the logic of the game should work.
Add an int score;
private void bCheck_Click(object sender, EventArgs e)
{
bool found = false;
foreach (Label l in pole)
{
if (l.Location == lblCovece.Location && l.Text == txtGoal.Text)
{
l.BackColor = Color.Green;
score += int.Parse(l.Text);
lblResultE.Text = score.ToString();
found = true;
}
}
if (!found)
{
score -= 10;
lblResultE.Text = score.ToString();
}
}
I would like to create a new dynamic chart control.
This chart will have a lot of code behind it that works out data calculations and then populates properties of the chart.
My form class is getting rather large and I'm now thinking of putting all this new code im going to create in a new class (possibly call it "DynmChart").
Normally to use controls I would create a new class and then instantiate the form in the new class.
But my form class is part of a winforms project that uses program.c as its main class.
main contains application.run Form1.
So how would I create all the code etc that calculates and then populates controls that are in my form.
Here's all my code.
2 classes
Form1
Program
namespace RepSalesNetAnalysis
{
public partial class Form1 : Form
{
float top = 0;
float tmid = 0;
float bmid = 0;
float bottom = 0;
float tempTop = 0;
float tempMidt = 0;
float tempMidB = 0;
float tempBot = 0;
string meh;
DataTable pgTable = new DataTable();
public Form1()
{
InitializeComponent();
pictureBox2.Visible = false;
}
//button to run SalesFigures
private void button1_Click_1(object sender, EventArgs e)
{
checkBox1.Checked = true;
string acct = accCollection.Text;
Task t = new Task(() => GetsalesFigures(acct));
t.Start();
}
//invoke method for setting the picture box visible(grabs the control out of the form to use in a thread)
private void SetPictureBoxVisibility(bool IsVisible)
{
if (pictureBox2.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetPictureBoxVisibility), new Object[] { IsVisible });
}
else
{
pictureBox2.Visible = IsVisible;
}
}
//invoke method for a check box toggle(to be used for testing
private void SetCheckBoxValue(bool IsChecked)
{
if (checkBox1.InvokeRequired)
{
pictureBox2.Invoke(new Action<bool>(SetCheckBoxValue), new Object[] { IsChecked });
}
else
{
checkBox1.Checked = IsChecked;
}
}
//invoke method to add customers and pass it to the sales method
private void AddItem(string value)
{
if (accCollection.InvokeRequired)
{
accCollection.Invoke(new Action<string>(AddItem), new Object[] { value });
}
else
{
accCollection.Items.Add(value);
}
}
//invoke method to set the datagrid properties
private void SetDataGrid(bool AutoGenerateColumns, Object DataSource, String DataMember, DataGridViewAutoSizeColumnsMode Mode)
{
if (this.dataGridView1.InvokeRequired)
{
this.dataGridView1.Invoke(new Action<bool, Object, String, DataGridViewAutoSizeColumnsMode>(SetDataGrid),
AutoGenerateColumns, DataSource, DataMember, Mode);
}
else
{
this.dataGridView1.AutoGenerateColumns = AutoGenerateColumns;
this.dataGridView1.DataSource = DataSource;
this.dataGridView1.DataMember = DataMember;
dataGridView1.AutoResizeColumns(Mode);
}
}
//on form load run the accounts too combco box method
private void Form1_Load(object sender, EventArgs e)
{
AutofillAccounts();
}
//method for task to get sales info
private void GetsalesFigures(string Acct)
{
try
{
string myConn = "Server=sgsg;" +
"Database=shaftdata;" +
"uid=bsgsg;" +
"pwd=drsgsg;" +
"Connect Timeout=120;";
string acct;// test using 1560
SqlConnection conn = new SqlConnection(myConn);
SqlCommand Pareto = new SqlCommand();
BindingSource bindme = new BindingSource();
SqlDataAdapter adapt1 = new SqlDataAdapter(Pareto);
DataSet dataSet1 = new DataSet();
DataTable table1 = new DataTable();
acct = Acct;
string fromDate = this.dateTimePicker1.Value.ToString("MM/dd/yyyy");
string tooDate = this.dateTimePicker2.Value.ToString("MM/dd/yyyy");
Pareto.Connection = conn;
Pareto.CommandType = CommandType.StoredProcedure;
Pareto.CommandText = "dbo.GetSalesParetotemp";
Pareto.CommandTimeout = 120;
Pareto.Parameters.AddWithValue("#acct", acct);
Pareto.Parameters.AddWithValue("#from", fromDate);
Pareto.Parameters.AddWithValue("#too", tooDate);
SetCheckBoxValue(true);
SetPictureBoxVisibility(true);
adapt1.Fill(dataSet1, "Pareto");
SetCheckBoxValue(false);
SetPictureBoxVisibility(false);
SetDataGrid(true, dataSet1, "Pareto", DataGridViewAutoSizeColumnsMode.AllCells);
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells);
}
catch (Exception execc)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + execc.Message + execc.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
//method non-task to get customer info
private void AutofillAccounts()
{
try
{
string myConn1 = "Server=sgsdg;" +
"Database=AutoPart;" +
"uid=bsgdg;" +
"pwd=dsgsg;" +
"Connect Timeout=6000;";
SqlConnection conn1 = new SqlConnection(myConn1);
conn1.Open();
SqlCommand accountFill = new SqlCommand("SELECT keycode FROM dbo.Customer", conn1);
SqlCommand pgFill = new SqlCommand("SELECT DISTINCT pg FROM dbo.Product", conn1);
SqlDataReader readacc = accountFill.ExecuteReader();
while (readacc.Read())
{
AddItem(readacc.GetString(0).ToString());
}
conn1.Close();
////////////////////////////////////////
conn1.Open();
SqlDataReader readpg = pgFill.ExecuteReader();
while (readpg.Read())
{
cmbPrdGrp.Items.Add(readpg.GetString(0).ToString());
}
conn1.Close();
}
catch(Exception exc1)
{
MessageBox.Show("Whoops! Seems we couldnt connect to the server!"
+ " information:\n\n" + exc1.Message + exc1.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
//spare method for testing
private void spare()
{
chartControl1.Series.Clear();
chartControl2.Series.Clear();
meh = cmbPrdGrp.Text;
bottom = 0;
bmid = 0;
tmid = 0;
top = 0;
double countTot = 0;
double countPg = 0;
double percent = 0;
//ok lets set the properties on click
//get pareto data from datagrid using count
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//count total
countTot++;
if ((string)row.Cells["Pg"].Value == meh)
{
//need to some how count pgs hmmmm
//countpg
countPg++;
if ((int)row.Cells["Pareto"].Value <= 50)
{
//top 50
//top++;
tempTop = Convert.ToSingle(row.Cells["Qty"].Value);
top += tempTop;
}
else
if (((int)row.Cells["Pareto"].Value > 50) && ((int)row.Cells["Pareto"].Value <= 100))
{
//50-100
tempMidt = Convert.ToSingle(row.Cells["Qty"].Value);
tmid += tempMidt;
}
else
if (((int)row.Cells["Pareto"].Value > 100) && ((int)row.Cells["Pareto"].Value <= 200))
{
//100-200
tempMidB = Convert.ToSingle(row.Cells["Qty"].Value);
bmid += tempMidB;
}
else
{
//its over 200!!!!!!!!!!!!!!
tempBot = Convert.ToSingle(row.Cells["Qty"].Value);
bottom += tempBot;
}
}
}
textBox1.Text = top.ToString();
textBox2.Text = tmid.ToString();
textBox3.Text = bmid.ToString();
textBox4.Text = bottom.ToString();
//calc percent
percent = (countPg / countTot);
//String.Format("{%#0:00}", percent);
//display counts as percentage of total
textBox5.Text = countTot.ToString();
textBox6.Text = percent.ToString("p1");
double[] yValues = { bottom, bmid, tmid, top };
string[] xNames = { "Greater than 200", "Between 200-100", "Between 100-50", "Below 50" };
//chart1.Series[0].Points.DataBindXY(xNames, yValues);
DataTable chartTable = new DataTable("Table1");
// Add two columns to the table.
chartTable.Columns.Add("Names", typeof(string));
chartTable.Columns.Add("Value", typeof(Int32));
chartTable.Rows.Add("Below 50", top);
chartTable.Rows.Add("Between 50-100", tmid);
chartTable.Rows.Add("Between 100-200", bmid);
chartTable.Rows.Add("Greater than 200", bottom);
Series series1 = new Series("Series1", ViewType.Pie3D);
Series series2 = new Series("Series2", ViewType.Bar);
chartControl2.Series.Add(series1);
chartControl1.Series.Add(series2);
series1.DataSource = chartTable;
series2.DataSource = chartTable;
series1.ArgumentScaleType = ScaleType.Qualitative;
series2.ArgumentScaleType = ScaleType.Qualitative;
series1.ArgumentDataMember = "names";
series2.ArgumentDataMember = "names";
series1.ValueScaleType = ScaleType.Numerical;
series2.ValueScaleType = ScaleType.Numerical;
series1.ValueDataMembers.AddRange(new string[] { "Value" });
series2.ValueDataMembers.AddRange(new string[] { "Value" });
//series1.Label.PointOptions.PointView = PointView.ArgumentAndValues;
series1.LegendPointOptions.PointView = PointView.ArgumentAndValues;
series2.LegendPointOptions.PointView = PointView.ArgumentAndValues;
series1.LegendPointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
series2.LegendPointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
series1.LegendPointOptions.ValueNumericOptions.Precision = 0;
series2.LegendPointOptions.ValueNumericOptions.Precision = 0;
// Adjust the value numeric options of the series.
series1.Label.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
//series2.Label.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
series1.Label.PointOptions.ValueNumericOptions.Precision = 0;
//series2.Label.PointOptions.ValueNumericOptions.Precision = 0;
// Adjust the view-type-specific options of the series.
((Pie3DSeriesView)series1.View).Depth = 20;
((Pie3DSeriesView)series1.View).ExplodedPoints.Add(series1.Points[0]);
((Pie3DSeriesView)series1.View).ExplodedPoints.Add(series1.Points[1]);
((Pie3DSeriesView)series1.View).ExplodedPoints.Add(series1.Points[2]);
((Pie3DSeriesView)series1.View).ExplodedPoints.Add(series1.Points[3]);
((Pie3DSeriesView)series1.View).ExplodedDistancePercentage = 20;
//((BarSeriesView)series2.View).
chartControl2.Legend.Visible = true;
chartControl1.Legend.Visible = true;
//series1.Label.PointOptions.ValueNumericOptions.Format = NumericFormat.Currency;
}
//spare button for testing
private void tempButton_Click(object sender, EventArgs e)
{
spare();
SpendsAnalysis();
}
private void Close_Click(object sender, EventArgs e)
{
Close();
}
private void Piebutton_Click(object sender, EventArgs e)
{
/*Rectangle tabArea;
RectangleF tabTextArea;
Bitmap B = new Bitmap(250, 250, PixelFormat.Format32bppArgb);
tabArea = new Rectangle(1, 1, 240, 240);
tabTextArea = new RectangleF(1, 1, 240, 240);
using (Graphics g = Graphics.FromImage(B))
{
int i1 = bottom;
int i2 = bmid;
int i3 = tmid;
int i4 = top;
float total = i1 + i2 + i3 + i4;
float deg1 = (i1 / total) * 360;
float deg2 = (i2 / total) * 360;
float deg3 = (i3 / total) * 360;
float deg4 = (i4 / total) * 360;
Font font = new Font("Arial", 10.0f);
SolidBrush brush = new SolidBrush(Color.Red);
Pen p = new Pen(Color.Empty, 0);
Brush b1 = new SolidBrush(Color.DarkRed);
Brush b2 = new SolidBrush(Color.DarkOrange);
Brush b3 = new SolidBrush(Color.DarkGray);
Brush b4 = new SolidBrush(Color.DarkViolet);
//g.DrawRectangle(p, tabArea);
g.DrawPie(p, tabTextArea, 0, deg1);
g.FillPie(b1, tabArea, 0, deg1);
g.DrawPie(p, tabTextArea, deg1, deg2);
g.FillPie(b2, tabArea, deg1, deg2);
g.DrawPie(p, tabTextArea, deg2 + deg1, deg3);
g.FillPie(b3, tabArea, deg2 + deg1, deg3);
g.DrawPie(p, tabTextArea, deg3 + deg2 + deg1, deg4);
g.FillPie(b4, tabArea, deg3 + deg2 + deg1, deg4);
//set picturebox3 as data source??
pictureBox3.Image = B;
textBox1.Text = top.ToString();
textBox2.Text = tmid.ToString();
textBox3.Text = bmid.ToString();
textBox4.Text = bottom.ToString();
//chart1.DataBind(x);
}*/
}
//need to create a more dynamic chart that will give details via PG.
//iether by internal filtering OR via queries(queries take time)
private void ChartByPrdGrp()
{
//sort data from frid via grp
foreach (DataGridViewRow pgrow in dataGridView1.Rows)
{
if ((string)pgrow.Cells["Pg"].Value == meh)
{
//add this row to new table called boots
pgTable.Rows.Add(dataGridView1.Rows);//this?
pgTable.Rows.Add(pgrow);//or this?
}
}
}
private void SpendsAnalysis()
{
float tempQtypg = 0;
float tempPricepg = 0;
double tempTotpg = 0;
double totalpg = 0;
float tempQty = 0;
float tempPrice = 0;
float tempTot = 0;
float total = 0;
float qtyPg = 0;
float qty = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
tempQty = Convert.ToSingle(row.Cells["Qty"].Value);
tempPrice = Convert.ToSingle(row.Cells["Unit"].Value);
tempTot = tempQty * tempPrice;
total += tempTot;
qty += tempQty;
if ((string)row.Cells["Pg"].Value == meh)
{
//tempQty = (float)row.Cells["Qty"].Value;
tempQtypg = Convert.ToSingle(row.Cells["Qty"].Value);
tempPricepg = Convert.ToSingle(row.Cells["Unit"].Value);
tempTotpg = tempQtypg * tempPricepg;
totalpg += tempTotpg;
qtyPg += tempQtypg;
}
}
textBox12.Text = total.ToString("c");
textBox7.Text = totalpg.ToString("c");
textBox13.Text = qty.ToString();
textBox8.Text = qtyPg.ToString();
}
}
}
program class is my MAIN class:
namespace RepSalesNetAnalysis
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
any help would be great!
Many Thanks in Advance!
If I'm understanding your question right...
DynmChart should probably be created as a UserControl and used on forms where it's needed.
However, if you stay with your current approach:
You can use Encapsulation to separate responsibilities between the Form1 class (or your UserControl if you go that route) and a new Calculation class. The UI class would be responsible for display tasks, while the Calculation class would be responsible for number crunching. Simply create an instance of Calculation in Form1/your UserControl and use the Calculation instance to return results of the various calculations you need.
If the UI portion of your control is becoming unmanageable in terms of the amount of code in one file, the first thing to consider is using #region directives to hide parts of the code you are not working on (organize the code into blocks that logically belong together).
Another approach, if you need a lot of UI code and it's bloating your class file, is to use Partial Classes.
I want to enable my start button after clicking all the three stop buttons.
I tried to place the button btn4.enabled = false inside the (sender == btn3), but the start button will be enabled if I first clicked on that button.
The three stop buttons can be clicked in random order.
Here's my code so far:
namespace SlotMachine
{
class SlotMac
{
private Form f;
Button btn1 = new Button(); // First stop
Button btn2 = new Button(); // Second stop
Button btn3 = new Button(); // Third stop
Button btn4 = new Button(); // Start
Timer Clock; // Tick
Timer Clock1; // Tick
Timer Clock2; // Tick
Int32 tick = 0;
Label tb = new Label();
int[] nNum = new int[3];
public SlotMac()
{
f = new Form();
f.Text = "Slot Machine";
//f.Size = new Size(800, 700);
f.FormBorderStyle = FormBorderStyle.FixedSingle;
}
PictureBox[] pics = new PictureBox[7];
PictureBox[] pics1 = new PictureBox[7];
PictureBox[] pics2 = new PictureBox[7];
//PictureBox pb = new PictureBox();
public void Launch()
{
Random r = new Random();
int i = 0;
//int x = 0;
//int x = 50;
tb.Location = new Point(205,20);
f.Controls.Add(tb);
Clock = new Timer();
Clock.Interval = 800;
Clock.Tick += new EventHandler(Clock_Tick);
Clock1 = new Timer();
Clock1.Interval = 800;
Clock1.Tick += new EventHandler(Clock1_Tick);
Clock2 = new Timer();
Clock2.Interval = 800;
Clock2.Tick += new EventHandler(Clock2_Tick);
for (i = 0; i < pics.Length; i++)
{
pics[i] = new PictureBox();
pics[0].Image = Image.FromFile(i + ".jpg");
pics[i].SetBounds(50, 100, 100, 100);
//x += 150;
f.Controls.Add(pics[i]);
}
for (i = 0; i < pics1.Length; i++)
{
pics1[i] = new PictureBox();
pics1[i].Image = Image.FromFile(i + ".jpg");
pics1[i].SetBounds(200, 100, 100, 100);
//x += 50;
f.Controls.Add(pics1[i]);
}
for (i = 0; i < pics2.Length; i++)
{
pics2[i] = new PictureBox();
pics2[i].Image = Image.FromFile(i + ".jpg");
pics2[i].SetBounds(350, 100, 100, 100);
//x += 50;
f.Controls.Add(pics2[i]);
}
f.SetBounds(10, 20, 500, 500);
// STOP
btn1.Location = new Point(50, 250);
btn1.Height = 40;
btn1.Width = 100;
f.Controls.Add(btn1);
btn1.Text = "STOP";
this.btn1.Click += new EventHandler(this.MyButtonClick);
// STOP
btn2.Location = new Point(200, 250);
btn2.Height = 40;
btn2.Width = 100;
btn2.Text = "STOP";
f.Controls.Add(btn2);
this.btn2.Click += new EventHandler(this.MyButtonClick);
// STOP
btn3.Location = new Point(350, 250);
btn3.Height = 40;
btn3.Width = 100;
btn3.Text = "STOP";
f.Controls.Add(btn3);
this.btn3.Click += new EventHandler(this.MyButtonClick);
// START
btn4.Location = new Point(200, 370);
btn4.Height = 40;
btn4.Width = 100;
btn4.Text = "START";
f.Controls.Add(btn4);
this.btn4.Click += new EventHandler(btn4_Click);
f.ShowDialog();
}
public void Clock_Tick(object sender, EventArgs e)
{
tick++;
Random r = new Random();
nNum[0] = r.Next(0, 6);
for (int i = 0; i < pics.Length; i++)
{
pics[0].Image = Image.FromFile(nNum[0] + ".jpg");
pics[1].Image = Image.FromFile(nNum[0] + ".jpg");
pics[2].Image = Image.FromFile(nNum[0] + ".jpg");
pics[3].Image = Image.FromFile(nNum[0] + ".jpg");
pics[4].Image = Image.FromFile(nNum[0] + ".jpg");
pics[5].Image = Image.FromFile(nNum[0] + ".jpg");
pics[6].Image = Image.FromFile(nNum[0] + ".jpg");
}
}
public void Clock1_Tick(object sender, EventArgs e)
{
tick++;
Random r = new Random();
nNum[1] = r.Next(0, 6);
for (int i = 0; i < pics.Length; i++)
{
pics1[0].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[1].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[2].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[3].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[4].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[5].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[6].Image = Image.FromFile(nNum[1] + ".jpg");
}
}
public void Clock2_Tick(object sender, EventArgs e)
{
tick++;
Random r = new Random();
nNum[2] = r.Next(0, 6);
for (int i = 0; i < pics.Length; i++)
{
pics2[0].Image = Image.FromFile(nNum[2] + ".jpg");
pics1[1].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[2].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[3].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[4].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[5].Image = Image.FromFile(nNum[1] + ".jpg");
pics1[6].Image = Image.FromFile(nNum[1] + ".jpg");
}
}
public void MyButtonClick(object sender, EventArgs e)
{
if (sender == btn1)
{
Clock.Stop();
}
if (sender == btn2)
{
Clock1.Stop();
}
if (sender == btn3)
{
Clock2.Stop();
}
Finish();
}
public void btn4_Click(object sender, EventArgs e)
{
Clock.Start();
Clock1.Start();
Clock2.Start();
btn4.Enabled = false;
}
public void Finish()
{
if (nNum[0] == nNum[1] && nNum[0] == nNum[2])
{
this.tb.Text = "Congratulations!";
}
}
}
}
You can check if all timers already stopped, like this:
public void MyButtonClick(object sender, EventArgs e)
{
if (sender == btn1)
{
Clock.Stop();
}
if (sender == btn2)
{
Clock1.Stop();
}
if (sender == btn3)
{
Clock2.Stop();
}
Finish();
if(!Clock.Enabled && !Clock1.Enabled && !Clock2.Enabled)
btn4.Enabled = true;
}
Try this for method MyButtonClick:
public void MyButtonClick(object sender, EventArgs e)
{
if (sender == btn1)
{
Clock.Stop();
}
if (sender == btn2)
{
Clock1.Stop();
}
if (sender == btn3)
{
Clock2.Stop();
}
Finish();
if (!Clock.Enabled && !Clock1.Enabled && !Clock2.Enabled) btn4.Enabled = true;
}
You could disable each button as they are clicked (which would make sense) and then after they are all disabled, enable the Start button.
if (sender == btn1)
{
Clock.Stop();
btn1.Enabled = false; // disable the buttons after they are clicked.
}
if (sender == btn2)
{
Clock1.Stop();
btn2.Enabled = false;
}
if (sender == btn3)
{
Clock2.Stop();
btn3.Enabled = false;
}
// If all buttons are disabled then enable the Start button.
if (!btn1.Enabled && !btn2.Enabled && !btn3.Enabled)
{
btn4.Enabled = true;
}
Finish();