hey guys i got a question right now I have a 8*8 array of buttons. They can change color by clicking on them. I want to make a reset button so when you click on the reset button they will return to the backcolor black again. Button1 is the reset button. it is at the bottum of the code.
Here is the code:
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"C:\testmap\test.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != btn.GetLength(0) * btn.GetLength(1) * 2)
return;
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value = ((char)data[2 * position]).ToString() + ((char)data[2 * position + 1]).ToString();
Color color;
switch (value)
{
case "01":
color = Color.Red;
break;
case "00":
color = Color.Black;
break;
case "10":
color = Color.Green;
break;
case "11":
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
Dictionary<Form1, int> d = new Dictionary<Form1, int>();
byte[] data = new byte[btn.GetLength(0) * btn.GetLength(1) * 2];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = "01";
break;
case "Black":
value = "00";
break;
case "Green":
value = "10";
break;
case "Yellow":
value = "11";
break;
default:
value = "00";
break;
}
data[2 * position] = (byte)value[0];
data[2 * position + 1] = (byte)value[1];
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
Just like you initialized the buttons, you can set the backcolor back to black:
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y].BackColor = Color.Black;
}
}
}
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
btn[i, j].BackColor = Color.Black;
}
}
but what have you tried?
http://msdn.microsoft.com/en-AU/library/system.windows.forms.control.tag.aspx
Assuming you are not intending to use the control's Tag property for anything else, you could consider setting all affiliated elements to a particular Tag and then iterating through the form's controls to reset them to the desired BackColor, or you could simply set the Tag as your desired BackColor and have the reset button iterate as desirred.
Related
I am writing some code in C# (Winforms .network). I get the error that pos does not exist in the current context. I understand the error, but I don't know how I can fix this. The error is in this part of the code:
if (j == x && i + pos == y)
{
label.BackColor = Color.Red;
}
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 System.Timers;
namespace TetrisBlok
{
public partial class Form1 : Form
{
private Label label;
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
}
public void Form1_Load(object sender, EventArgs e)
{
int[,] matrix = {
{0, 1, 0},
{0, 1, 0},
{0, 1, 1}};
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 20; j++)
{
label = new Label();
label.AutoSize = false;
label.Name = "label" + j.ToString() + i.ToString();
label.TabIndex = 0;
label.Text = "[" + j.ToString() + "]" + "[" + i.ToString() + "]";
label.Visible = true;
this.Controls.Add(label);
label.Location = new Point(Size.Width / 2 - (5 - i) * 50, Size.Height / 2 - (11 - j) * 30);
label.Size = new Size(50, 30);
label.BackColor = Color.White;
if (i % 2 == 0)
{
label.BackColor = Color.Blue;
}
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
if (matrix[x, y].Equals(1))
{
if (j == x && i + pos == y)
{
label.BackColor = Color.Red;
}
}
}
}
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int pos = 0;
if (e.KeyCode == Keys.Right)
{
pos = 1;
}
}
}
}
I get the error because I make int pos in the Form1_KeyDown. What must I change so I can use the int pos in the Form1_Load and the Form_KeyDown?
I want that whenever I press the right arrow key, int pos will increase by 1. Then I want to use that value in the Form1_Load so I can move something.
I have a 2d array of LEDButton : Button.
I want to find out the index [x,y] of each buttons the user clicks.
I am new to Windows Forms and not used to working outside of a console so these GUI objects are very unfamiliar to me.
private void Form1_Load(object sender, EventArgs e)
{
LEDButton[,] leds = new LEDButton[11, 11];
for (int x = 0; x < leds.GetUpperBound(0); x++)
{
listBox1.Items.Add("x = " + x);
for (int y = 0; y < leds.GetUpperBound(1); y++)
{
leds[x, y] = new LEDButton()
{
Name = String.Format("Button{0}{1}", x, y),
TabIndex = 40 * x + y,
Location = new Point(40 * y + 50, 40 * x + 50)
};
leds[x, y].pointx = x;
leds[x, y].pointy = y;
}
}
// add buttons to controls
for (int x = 0; x < leds.GetUpperBound(0); x++)
{
for (int y = 0; y < leds.GetUpperBound(1); y++)
{
Controls.Add(leds[x, y]);
leds[x, y].Click += Form1_Click;
}
}
public class LEDButton : Button
{
public const int LEDWidth = 20;
public const int LEDHeight = 20;
public int pointx = 0;
public int pointy = 0;
public LEDButton()
{
BackColor = Color.FromArgb(0, 64, 0);
ForeColor = Color.Black;
FlatStyle = FlatStyle.Flat;
Size = new Size(LEDWidth, LEDHeight);
UseVisualStyleBackColor = false;
this.Click += LEDButton_Click; //throws error
}
}
I think I found my answer with the help of Lars.
Code should be
private void Form1_Click(object? sender, EventArgs e)
{
LEDButton btn = sender as LEDButton;
listBox2.Items.Add(btn.Name);
}
I have a chart on my c# windows application.
I want to zoom every point of chart when mouse on them.
like google map
I mean I don't want zoom all part of chart
I want zoom just specefic point like google map
code:
public partial class Form1 : Form
{
int[] myArrayX = new int[5];
double[] myArrayY = new double[5];
int lastX = -1;
double lastY = -0.6;
double xmax;
Graph.Chart chart;
public Form1()
{
InitializeComponent();
this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
}
void Form1_MouseWheel(object sender, MouseEventArgs e)
{
try
{
if (e.Delta > 0)
{
double xMin = chart.ChartAreas["draw"].AxisX.ScaleView.ViewMinimum;
double xMax = chart.ChartAreas["draw"].AxisX.ScaleView.ViewMaximum;
double yMin = chart.ChartAreas["draw"].AxisY.ScaleView.ViewMinimum;
double yMax = chart.ChartAreas["draw"].AxisY.ScaleView.ViewMaximum;
double posXStart = chart.ChartAreas["draw"].AxisX.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 2;
double posXFinish = chart.ChartAreas["draw"].AxisX.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 2;
double posYStart = chart.ChartAreas["draw"].AxisY.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 2;
double posYFinish = chart.ChartAreas["draw"].AxisY.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 2;
chart.ChartAreas["draw"].AxisX.ScaleView.Zoom(posXStart, posXFinish);
chart.ChartAreas["draw"].AxisY.ScaleView.Zoom(posYStart, posYFinish);
}
else if (e.Delta < 0)
{
ZoomOut();
}
}
catch { }
}
private void ZoomOut()
{
chart.ChartAreas["draw"].AxisX.ScaleView.ZoomReset();
chart.ChartAreas["draw"].AxisY.ScaleView.ZoomReset();
}
void CreateNewGraph()
{
// Create new Graph
chart = new Graph.Chart();
chart.Location = new System.Drawing.Point(13, 185);
chart.Size = new System.Drawing.Size(900, 500);
chart.ChartAreas.Add("draw");
chart.ChartAreas["draw"].AxisX.Minimum = 0;
chart.ChartAreas["draw"].AxisX.Maximum = 20;
chart.ChartAreas["draw"].AxisX.Interval = 1;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineColor = Color.White;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
chart.ChartAreas["draw"].AxisY.Minimum = -0.4;
chart.ChartAreas["draw"].AxisY.Maximum = 1;
chart.ChartAreas["draw"].AxisY.Interval = 0.2;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineColor = Color.White;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
chart.ChartAreas["draw"].BackColor = Color.Black;
var series = chart.Series.Add("Test");
chart.Series["Test"].ChartType = Graph.SeriesChartType.Line;
chart.Series["Test"].Color = Color.Yellow;
chart.Series["Test"].BorderWidth = 3;
chart.Legends.Add("MyLegend");
chart.Legends["MyLegend"].BorderColor = Color.YellowGreen;
// Set automatic zooming
chart.ChartAreas["draw"].AxisX.ScaleView.Zoomable = true;
chart.ChartAreas["draw"].AxisY.ScaleView.Zoomable = true;
// Set automatic scrolling
chart.ChartAreas["draw"].CursorX.AutoScroll = true;
chart.ChartAreas["draw"].CursorY.AutoScroll = true;
// Allow user selection for Zoom
chart.ChartAreas["draw"].CursorX.IsUserSelectionEnabled = true;
chart.ChartAreas["draw"].CursorY.IsUserSelectionEnabled = true;
chart.ChartAreas["draw"].AxisX.ScaleView.Zoomable = true;
chart.ChartAreas["draw"].AxisY.ScaleView.Zoomable = true;
//chart.MouseWheel += new MouseEventHandler(chart_MouseWheel);
}
private void Form1_Load(object sender, EventArgs e)
{
CreateNewGraph();
}
private void timer1_Tick(object sender, EventArgs e)
{
fillarray();
for (int i = 1; i <= 5; i += 1)
{
chart.Series["Test"].Points.AddXY(myArrayX[i - 1], myArrayY[i - 1]);
xmax = myArrayX[i - 1];
}
if (xmax >= 20)
{
chart.ChartAreas["draw"].AxisX.ScrollBar.Enabled = true;
chart.ChartAreas["draw"].AxisX.ScaleView.Zoomable = true;
chart.ChartAreas["draw"].AxisX.ScaleView.Zoom(0, xmax);
}
Controls.Add(this.chart);
}
public void fillarray()
{
for (int i = 1; i <= 5; i += 1)
{
lastX = lastX + 1;
myArrayX[i - 1] = lastX;
}
for (int i = 1; i < 5; i += 1)
{
lastY = lastY + 0.2;
myArrayY[i - 1] = lastY;
}
}
}
Asuming that you use the "standard" (since .NET 4.0) Charting Lib which is in the namespace System.Windows.Forms.DataVisualization.Charting. You can implement custom interactivity (zoom when mouse does this or that). MSDN is a good start and GIYF.
http://msdn.microsoft.com/en-us/library/dd456772(v=vs.110).aspx
There are also a lot of examples around the web.
good luck!
I am trying to make a simple tile game engine and running into issues. I get stuck when i have to redraw the tile.
int[,] level = {
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
};
This is my array and all the values are 0 thus off. Each corresponding value is linked to a seperate tile that will turn on and off as you press the keys.
//Event Handler (W,A,S,D) is used for movements
private void panel1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
.
.
.
}
//Responsible for movements
private void tmrMov_Tick(object sender, EventArgs e)
{
level[_x, _y] = 0;
if (_objDirection == Direction.Right)
{
if (_x < _boardWidth - 1 && _x >= 0 && _x + 1 < _boardWidth - 1 && _x + 1 >= 0)
_x += 1;
else
_x = _boardWidth - 1;
}
.
.
.
level[_x, _y] = _k;
Invalidate();
}
This is my timer function that is supposed to 'manipulate' array values so when the program is running, one can decide which tile to turn on/off through keys.
Anyways, my problem is refreshing the image which concerns the 'invalidate()' function call. Though, i do have a feeling it can change array values on the fly, i can't seem to refresh the image to jump to another tile.
Here's the link to the complete project i've been working on: http://www.mediafire.com/?g10a0zzt8hru11v
Here's a similar but different question i asked some days back: Setting up basic game and debugging fundamental problems
Thanks in advance!
So...I hope you don't take any offense to this, but I went through and tidied things up a bit and offered some suggestions/fixes/comments/etc.
Hope this helps! Let me know if any of the suggested changes need explanation.
So, let's start at the designer.cs file:
// Ahh, here's yer problem: the panel control doesn't raise PreviewKeyDowns - the form does, tho
this.panel1.PreviewKeyDown +=
new System.Windows.Forms.PreviewKeyDownEventHandler(
this.panel1_PreviewKeyDown);
// the form will raise these, so bind the handler to it
// (and rename the method)
this.PreviewKeyDown +=
new System.Windows.Forms.PreviewKeyDownEventHandler(
this.Form1_PreviewKeyDown);
Ah, one big problem down - none of your key events were actually getting to your handler. Let's pop back over to the form code-behind.
So, in the constructor - all this can go:
// arrays of T (T[], int[], etc), come initialized to default(T),
// so none of this is needed.
level[0, 0] = 0;
level[0, 1] = 0;
level[0, 2] = 0;
level[0, 3] = 0;
level[0, 4] = 0;
Jump down to the Paint handler:
// The next two checks have the x and y swapped,
// meaning the apparent motion will not match what the
// actual direction should be
//Empty Tile
if (level[y, x] == 0)
{
//Occupied Tile
if (level[y, x] == 1)
{
// Now the render will mactch properly
//Empty Tile
if (level[x, y] == 0)
{
//Occupied Tile
if (level[x, y] == 1)
{
Onward! To the Timer.Tick handler:
#region Timer function
// doing this could cause flickering
// or flashing if the paint fires while
// we're updating things
level[_x, _y] = 0;
#region Timer function
// instead, keep track temporarily
// what they were - we'll come back to this later on
var oldX = _x;
var oldY = _y;
Further on to the if/else chains:
// There's a lot of replication and style choices here that
// will make it harder to debug/troubleshoot
if (_objDirection == Direction.Right)
{
if (_x < _boardWidth - 1 && _x >= 0 && _x + 1 < _boardWidth - 1 && _x + 1 >= 0)
_x += 1;
else
_x = _boardWidth - 1;
}
else if (_objDirection == Direction.Left)
Let's see if we can get rid of some of the repetition:
// let's figure these out ahead of time
var spaceOnLeft = _x > 0;
var spaceOnRight = _x < _boardWidth - 1;
var spaceOnTop = _y > 0;
var spaceOnBottom = _y < _boardHeight - 1;
// switch is a bit like the if/else construct you had
switch (_objDirection)
{
case Direction.Up:
// this means: if(spaceOnTop) y = y-1 else y = height-1
_y = spaceOnTop ? _y - 1 : _boardHeight - 1;
break;
case Direction.Down:
_y = spaceOnBottom ? _y + 1 : 0;
break;
case Direction.Left:
_x = spaceOnLeft ? _x - 1 : _boardWidth - 1;
break;
case Direction.Right:
_x = spaceOnRight ? _x + 1 : 0;
break;
}
Skip to the end...
// now we'll use the old position to clear...
level[oldX, oldY] = 0;
// then set the new position
level[_x, _y] = _k;
// Since we're only writing on the panel,
// we only need to rerender the panel
panel1.Refresh();
One last bit - the key down handler:
// Hah - artificial difficulty due
// to awkward key choice? Out of curiosity,
// why not Keys.Up, Down, Left, Right?
if (e.KeyCode == Keys.E)
{
_objDirection = Direction.Left;
}
else if (e.KeyCode == Keys.D)
{
_objDirection = Direction.Right;
}
else if (e.KeyCode == Keys.W)
{
_objDirection = Direction.Up;
}
else if (e.KeyCode == Keys.S)
{
_objDirection = Direction.Down;
}
// same deal here, but with keys
// Or switch to Up, Down, Left, Right :)
switch (e.KeyCode)
{
case Keys.E:
_objDirection = Direction.Up;
break;
case Keys.D:
_objDirection = Direction.Down;
break;
case Keys.W:
_objDirection = Direction.Left;
break;
case Keys.S:
_objDirection = Direction.Right;
break;
}
Full code drop of the Form1.cs class:
//Listing all the parameters
public partial class Form1 : Form
{
#region Declaring Parameters
enum Direction
{
Left, Right, Up, Down
}
private int _x;
private int _y;
private int _k;
private Direction _objDirection;
Random rand = new Random();
private int _boardWidth;
private int _boardHeight;
private int[,] level;
#endregion
//Giving values to parameters
public Form1()
{
InitializeComponent();
#region Initialial values
_k = 1;
_boardWidth = 6;
_boardHeight = 6;
_x = rand.Next(0, _boardWidth - 1);
_y = rand.Next(0, _boardHeight - 1);
_objDirection = Direction.Left;
//Array that works as a board or platform which we used to distinguish tiles
level = new int[_boardWidth, _boardHeight];
#endregion
}
//Paint is used for drawing purposes only
private void panel1_Paint(object sender, PaintEventArgs e)
{
/*
int[,] level = {
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
{ 0, 0, 0, 0, 0 ,0 },
};
*/
#region Looping through tiles
//Initializing first randomly filled tile
level[_x, _y] = _k;
for (int y = 0; y < _boardHeight; y++)
{
for (int x = 0; x < _boardWidth; x++)
{
//Empty Tile
if (level[x, y] == 0)
{
// Create pen.
Pen redPen = new Pen(Color.Red, 1);
// Create rectangle.
Rectangle redRect = new Rectangle(x * 50, y * 50, 50, 50);
// Draw rectangle to screen.
e.Graphics.DrawRectangle(redPen, redRect);
}
//Occupied Tile
if (level[x, y] == 1)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create rectangle.
Rectangle rect = new Rectangle(x * 50, y * 50, 50, 50);
// Fill rectangle to screen.
e.Graphics.FillRectangle(blueBrush, rect);
}
}
}
#endregion
}
//Responsible for movements
private void tmrMov_Tick(object sender, EventArgs e)
{
#region Timer function
// instead, keep track temporarily
// what they were
var oldX = _x;
var oldY = _y;
// let's figure these out ahead of time
var spaceOnLeft = _x > 0;
var spaceOnRight = _x < _boardWidth - 1;
var spaceOnTop = _y > 0;
var spaceOnBottom = _y < _boardHeight - 1;
// switch is a bit like the if/else construct you had
switch (_objDirection)
{
case Direction.Up:
// this means: if(spaceOnTop) y = y-1 else y = height-1
_y = spaceOnTop ? _y - 1 : _boardHeight - 1;
break;
case Direction.Down:
_y = spaceOnBottom ? _y + 1 : 0;
break;
case Direction.Left:
_x = spaceOnLeft ? _x - 1 : _boardWidth - 1;
break;
case Direction.Right:
_x = spaceOnRight ? _x + 1 : 0;
break;
}
// now we'll use the old values to clear...
level[oldX, oldY] = 0;
// then set the new value
level[_x, _y] = _k;
#endregion
panel1.Refresh();
}
//Event Handler (W,A,S,D) is used for movements
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
#region Controls
// same deal here, but with keys
switch (e.KeyCode)
{
case Keys.Up:
e.IsInputKey = true;
_objDirection = Direction.Up;
break;
case Keys.Down:
e.IsInputKey = true;
_objDirection = Direction.Down;
break;
case Keys.Left:
e.IsInputKey = true;
_objDirection = Direction.Left;
break;
case Keys.Right:
e.IsInputKey = true;
_objDirection = Direction.Right;
break;
}
#endregion
}
}
Cheers!
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm making an application for a ledcube in C#.
All it does now is allow the user to click on some buttons to change the color of the desired led's.
I'm trying to imply a function which allows the user to save the current configuration (of colors) to a file, which later can be read by a programming bord.
The saved file must contain binary code for each led (whether the led is on, and which color: off, red, green, orange).
I was thinking that 1 led can contain a value between 00 - 11 (so 0 and 3).
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] laag_1 = new Button[8, 8];
Button[,] laag_2 = new Button[8, 8];
Button[,] laag_3 = new Button[8, 8];
Button[,] laag_4 = new Button[8, 8];
Button[,] laag_5 = new Button[8, 8];
Button[,] laag_6 = new Button[8, 8];
Button[,] laag_7 = new Button[8, 8];
Button[,] laag_8 = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_1[x, y] = new Button();
laag_1[x, y].SetBounds((50 * x) + 100, (50 * y) + 30, 40, 40);
laag_1[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_1[x, y]);
laag_1[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_2.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_2[x, y] = new Button();
laag_2[x, y].SetBounds((50 * x) + 520, (50 * y) + 30, 40, 40);
laag_2[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_2[x, y]);
laag_2[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_3.GetLength(0); x++)
{
for (int y = 0; y < laag_3.GetLength(1); y++)
{
laag_3[x, y] = new Button();
laag_3[x, y].SetBounds((50 * x) + 940, (50 * y) + 30, 40, 40);
laag_3[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_3[x, y]);
laag_3[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_4.GetLength(0); x++)
{
for (int y = 0; y < laag_4.GetLength(1); y++)
{
laag_4[x, y] = new Button();
laag_4[x, y].SetBounds((50 * x) + 1360, (50 * y) + 30, 40, 40);
laag_4[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_4[x, y]);
laag_4[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_5.GetLength(0); x++)
{
for (int y = 0; y < laag_5.GetLength(1); y++)
{
laag_5[x, y] = new Button();
laag_5[x, y].SetBounds((50 * x) + 100, (50 * y) + 520, 40, 40);
laag_5[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_5[x, y]);
laag_5[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_6.GetLength(0); x++)
{
for (int y = 0; y < laag_6.GetLength(1); y++)
{
laag_6[x, y] = new Button();
laag_6[x, y].SetBounds((50 * x) + 520, (50 * y) + 520, 40, 40);
laag_6[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_6[x, y]);
laag_6[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_7.GetLength(0); x++)
{
for (int y = 0; y < laag_7.GetLength(1); y++)
{
laag_7[x, y] = new Button();
laag_7[x, y].SetBounds((50 * x) + 940, (50 * y) + 520, 40, 40);
laag_7[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_7[x, y]);
laag_7[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_8.GetLength(0); x++)
{
for (int y = 0; y < laag_8.GetLength(1); y++)
{
laag_8[x, y] = new Button();
laag_8[x, y].SetBounds((50 * x) + 1360, (50 * y) + 520, 40, 40);
laag_8[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(laag_8[x, y]);
laag_8[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"C:\testmap\laag_1.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != laag_1.GetLength(0) * laag_1.GetLength(1) * 2)
return;
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
int position = (y * laag_1.GetLength(0) + x);
string value = ((char)data[2 * position]).ToString() + ((char)data[2 * position + 1]).ToString();
Color color;
switch (value)
{
case "01":
color = Color.Red;
break;
case "00":
color = Color.Black;
break;
case "10":
color = Color.Green;
break;
case "11":
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
laag_1[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
Dictionary<Form1, int> d = new Dictionary<Form1, int>();
byte[] data = new byte[laag_1.GetLength(0) * laag_1.GetLength(1) * 2];
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
int position = (y * laag_1.GetLength(0) + x);
string value;
switch (laag_1[x, y].BackColor.Name)
{
case "Red":
value = "01";
break;
case "Black":
value = "00";
break;
case "Green":
value = "10";
break;
case "Yellow":
value = "11";
break;
default:
value = "00";
break;
}
data[2 * position] = (byte)value[0];
data[2 * position + 1] = (byte)value[1];
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < laag_1.GetLength(0); x++)
{
for (int y = 0; y < laag_1.GetLength(1); y++)
{
laag_1[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_2.GetLength(0); x++)
{
for (int y = 0; y < laag_2.GetLength(1); y++)
{
laag_2[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_3.GetLength(0); x++)
{
for (int y = 0; y < laag_3.GetLength(1); y++)
{
laag_3[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_4.GetLength(0); x++)
{
for (int y = 0; y < laag_4.GetLength(1); y++)
{
laag_4[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_5.GetLength(0); x++)
{
for (int y = 0; y < laag_5.GetLength(1); y++)
{
laag_5[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_6.GetLength(0); x++)
{
for (int y = 0; y < laag_6.GetLength(1); y++)
{
laag_6[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_7.GetLength(0); x++)
{
for (int y = 0; y < laag_7.GetLength(1); y++)
{
laag_7[x, y].BackColor = Color.Black;
}
}
for (int x = 0; x < laag_8.GetLength(0); x++)
{
for (int y = 0; y < laag_8.GetLength(1); y++)
{
laag_8[x, y].BackColor = Color.Black;
}
}
}
}
}
You could take a look at the File.WriteAllBytes and File.ReadAllBytes methods for saving and loading of the file.
Also take a look at the OpenFileDialog control for choosing what file to open.
Further, there's no need to be stingy with values, you can (and should) use a full byte for every button, just loop the buttons and insert the values in a byte[], and then write them out to a file.
I assume You want to use Object Serialization for this.
XMLSerialization: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization
BinarySerialization: http://msdn.microsoft.com/en-us/library/72hyey7b(v=vs.71).aspx
If you want to save data and then read it by another application I am suggesting you a Serialization, because You don't have to worry about reading from file.
Try this:
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
byte[] data = System.IO.File.ReadAllBytes(filePath);
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
int index = position / 8;
int shift = position % 8;
byte value = (byte)((data[index] >> shift) % 4);
Color color;
switch (value)
{
case 1:
color = Color.Red;
break;
case 0:
color = Color.Black;
break;
case 2:
color = Color.Green;
break;
case 3:
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[(7 + btn.GetLength(0) * btn.GetLength(1) * 2) / 8];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
byte value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = 1;
break;
case "Black":
value = 0;
break;
case "Green":
value = 2;
break;
case "Yellow":
value = 3;
break;
default:
value = 0;
break;
}
int index = position / 8;
int shift = position % 8;
data[index] = (byte)(data[index] | (value << shift));
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
[Updated]:
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
if (System.IO.File.Exists(filePath))
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
byte[] data = System.IO.File.ReadAllBytes(filePath);
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
int index = position / 8;
int shift = position % 8;
byte value = (byte)((data[index] >> shift) % 4);
Color color;
switch (value)
{
case 1:
color = Color.Red;
break;
case 0:
color = Color.Black;
break;
case 2:
color = Color.Green;
break;
case 3:
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[(7 + btn.GetLength(0) * btn.GetLength(1) * 2) / 8];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (x * btn.GetLength(1) + y) * 2;
byte value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = 1;
break;
case "Black":
value = 0;
break;
case "Green":
value = 2;
break;
case "Yellow":
value = 3;
break;
default:
value = 0;
break;
}
int index = position / 8;
int shift = position % 8;
data[index] = (byte)(data[index] | (value << shift));
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}
[Update #2] Reworking storage as full byte for each led:
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != btn.GetLength(0) * btn.GetLength(1))
return;
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
char value = (char)data[position];
Color color;
switch (value)
{
case '1':
color = Color.Red;
break;
case '0':
color = Color.Black;
break;
case '2':
color = Color.Green;
break;
case '3':
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
byte[] data = new byte[btn.GetLength(0) * btn.GetLength(1)];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
char value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = '1';
break;
case "Black":
value = '0';
break;
case "Green":
value = '2';
break;
case "Yellow":
value = '3';
break;
default:
value = '0';
break;
}
data[position] = (byte)value;
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}
Update #3:
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;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
btn[x, y] = new Button();
btn[x, y].SetBounds((50 * x) + 30, (50 * y) + 30, 40, 40);
btn[x, y].Click += new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Black;
}
}
this.FormClosing += new FormClosingEventHandler(this.SaveEventHandler);
LoadFromFile();
}
void btnEvent_click(object sender, EventArgs e)
{
Control ctrl = ((Control)sender);
switch (ctrl.BackColor.Name)
{
case "Red":
ctrl.BackColor = Color.Green;
break;
case "Black":
ctrl.BackColor = Color.Red;
break;
case "Green":
ctrl.BackColor = Color.Yellow;
break;
case "Yellow":
ctrl.BackColor = Color.Black;
break;
default:
ctrl.BackColor = Color.Black;
break;
}
}
void SaveEventHandler(object sender, EventArgs e)
{
SaveToFile();
}
private const string filePath = #"d:\test.txt";
private void LoadFromFile()
{
if (!System.IO.File.Exists(filePath))
return;
byte[] data = System.IO.File.ReadAllBytes(filePath);
if (data == null || data.Length != btn.GetLength(0) * btn.GetLength(1) * 2)
return;
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value = ((char)data[2 * position]).ToString() + ((char)data[2 * position + 1]).ToString();
Color color;
switch (value)
{
case "01":
color = Color.Red;
break;
case "00":
color = Color.Black;
break;
case "10":
color = Color.Green;
break;
case "11":
color = Color.Yellow;
break;
default:
color = Color.Black;
break;
}
btn[x, y].BackColor = color;
}
}
}
private void SaveToFile()
{
Dictionary<Form1, int> d = new Dictionary<Form1, int>();
byte[] data = new byte[btn.GetLength(0) * btn.GetLength(1) * 2];
for (int x = 0; x < btn.GetLength(0); x++)
{
for (int y = 0; y < btn.GetLength(1); y++)
{
int position = (y * btn.GetLength(0) + x);
string value;
switch (btn[x, y].BackColor.Name)
{
case "Red":
value = "01";
break;
case "Black":
value = "00";
break;
case "Green":
value = "10";
break;
case "Yellow":
value = "11";
break;
default:
value = "00";
break;
}
data[2 * position] = (byte)value[0];
data[2 * position + 1] = (byte)value[1];
}
}
System.IO.File.WriteAllBytes(filePath, data);
}
}
}