Image Appearing without being called - c#

I am making a whack a mole game, I can not use MVVM, and I am making a random mole image appear at a random time but when I start the game, one or sometimes two moles appear, that are not apart of that code (I have it so that when you click a mole, it will disappear, these unwanted moles do not disappear if clicked). Thank you for your help! I have added all of my Grid Population code, which is probably where the problem lies.
Code:
private void PopulateGrid()
{
MoleChanges = TUtils.GetIniInt(Moleini, "MoleChangeTimes", "AmountofChanges", 50);
ImageSize = TUtils.GetIniInt(Moleini, "ImageSize", "imageSize", 10);
NumofImages = TUtils.GetIniInt(Moleini, "NumPictures", "pictures", 8);
int ImageBorderSize = TUtils.GetIniInt(Moleini, "ImageBorder", "imageBorder", 2);
NumberOfColumns = TUtils.GetIniInt(Moleini, "NumRowsColumns", "columnNum", 4);
ImageHeight = ImageSize * 0.7;
// More Columns than Rows \\
if (NumberOfColumns > NumofImages)
{
MessageBox.Show("There is something wrong with the .ini file.");
MainWin.Close();
}
// Math - Get Necessary Variables \\
int ColumnSize = (ImageSize + (2 * ImageBorderSize));
int RowSize = (ImageSize + (2 * ImageBorderSize));
NumberofRows = (int)Math.Ceiling(NumofImages / NumberOfColumns);
int MainWindowWidth = (TUtils.ToInt(NumberOfColumns.ToString(), 2) * ColumnSize) + 15;
int MainWindowHeight = (NumberofRows * RowSize) + 200;
// Set Window Size \\
MainWin.Width = MainWindowWidth;
MainWin.Height = MainWindowHeight;
// Create Grid \\
Content_Grid.Children.Add(grid_Main);
grid_Main.Height = MainWindowHeight;
grid_Main.Width = MainWindowWidth;
grid_Main.Background = Brushes.Transparent;
// Grid Properties \\
for (int i = 0; i < NumberOfColumns; i++)
{
ColumnDefinition newColumn = new ColumnDefinition();
newColumn.Width = new GridLength(ColumnSize, GridUnitType.Pixel);
grid_Main.ColumnDefinitions.Add(newColumn);
}
for (int i = 0; i < NumberofRows; i++)
{
RowDefinition Row = new RowDefinition();
Row.Height = new GridLength(RowSize, GridUnitType.Pixel);
grid_Main.RowDefinitions.Add(Row);
}
// Fill Grid \\
int RowCount = 0;
int ColumnCount = 0;
for (int i = 0; i <= NumofImages; i++)
{
Image newImage = HoleImage();
if (RowCount < NumberofRows)
{
if (ColumnCount < NumberOfColumns)
{
Console.WriteLine("ColumnCount: " + ColumnCount.ToString());
Grid.SetRow(newImage, RowCount);
Grid.SetColumn(newImage, ColumnCount);
grid_Main.Children.Add(newImage);
ColumnCount++;
}
else
{
RowCount++;
ColumnCount = 0;
Grid.SetRow(newImage, RowCount);
Grid.SetColumn(newImage, ColumnCount);
grid_Main.Children.Add(newImage);
ColumnCount++;
Console.WriteLine("RowCount: " + RowCount.ToString());
}
}
else
{
break;
}
ChangeImage();
}
}
// Create Image for "Hut" \\
private Image HoleImage()
{
// Initialize Image \\
Image newImage = new Image();
// Image Properties \\
newImage.Width = ImageSize;
newImage.Height = ImageHeight;
// Define Name and Content \\
newImage.Name = "Image";
String ImageFunction = TUtils.GetIniString(Moleini, "ImagePath", "Hole", Root + "hole.jpg");
if (File.Exists(ImageFunction))
{
newImage.Source = new BitmapImage(new Uri(ImageFunction));
}
else
{
MessageBox.Show("Cannot find " + ImageFunction + ".", "Please fix the ini file");
}
return newImage;
}
// Change Image from "Hut" to Mole \\
private void ChangeImage()
{
Image newImage = HoleImage();
molePopup = MoleImage();
int numCol = Convert.ToInt32(NumberOfColumns);
//Random Number - Col
Random randomColumns = new Random();
int ranCol = randomColumns.Next(1, numCol);
//Random Number - Row
Random randomRow = new Random();
int ranRow = randomRow.Next(1, NumberofRows);
string Moleimage = TUtils.GetIniFileString(Moleini, "ImagePath", "PictureFile", Root + "mole2.png");
//Populate Grid with Mole at Random Times \\
Grid.SetRow(molePopup, ranRow);
Grid.SetColumn(molePopup, ranCol);
grid_Main.Children.Add(molePopup);
molePopup.MouseUp += new MouseButtonEventHandler((o, e) =>
{
MolePoints++;
grid_Main.Children.Remove(molePopup);
});
}

After a quick read over my gut reaction is that your ChangeImage() method is being called on each pass over the grid, causing a "random" cell to be "mole'd".
As for the click not working, I don't have VS to hand so can't be 100% on this but when you pass molePopup to grid_Mail.Children.Add it could be being passed as a value parameter meaning that your MouseUp handler is not actually there when the object is "copied" over to the grid.

Related

Infinite pages generated with e.HasMorePages

I generate several QRCodes and would like to print the barcodes one after another on an A4 size page in Print Preview Control. I also use this control: PrintBar
I calculated, that about 5 QRCodes can be on an A4 format page, so I tried to split with HasMorePages.
Print Preview without HasMorePages: the A4 page with the QRCodes screenshot - the last QRCode should be on the last page.
I added e.HasMorePages and return, but is not working correctly...It counts the pages to infinite and after that crashes.
My code:
BeginPrint
private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
this.currentItem = 0;
}
PrintPage
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String fontName = "Arial";
Font fontNormal = new Font(fontName, 12, System.Drawing.FontStyle.Regular);
float itemHeight = fontNormal.GetHeight(e.Graphics);
Brush normalColour = Brushes.Black;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
float printWidth = e.MarginBounds.Width;
float printHeight = e.MarginBounds.Height;
float rightMargin = leftMargin + printWidth;
float currentPosition = topMargin;
float numberWidth = 70;
float lineWidth = printWidth - numberWidth;
float lineLeft = leftMargin;
float numberLeft = leftMargin + lineWidth;
int items = 0;
foreach (DataRow dr in dt.Rows)
{
if (!dr[4].Equals(""))
items += Convert.ToInt32(dr[4].ToString());
else
items += 0;
}
noOfItems = items;
foreach (DataRow dr in dt.Rows)
{
Bitmap bt = null;
if (!dr[1].Equals(""))
{
if (!dr[4].Equals(""))
{
int nrcodes = Convert.ToInt32(dr[4].ToString());//in the 4th row the value means how many QRCodes should be generated
for (int i = 0; i < nrcodes; i++)
{
if (i % 5 != 0)
{
bt = GenerateQRCODE(dr[1].ToString());//dr[1] QRCode value
e.Graphics.DrawImage(bt, leftMargin, currentPosition, 200, 200);
e.Graphics.DrawString(dr[1].ToString(), fontNormal, normalColour, leftMargin + 40, currentPosition + 180); //dr[1] - text under QR Code
}
else
{
e.HasMorePages = true;
return;
}
currentPosition += 200;
}
}
}
}
// e.HasMorePages = true;
}
Yes, I need to print the same QR Code as many times as in the dr[4] column value. After that the next QR Code the same way.
In this case you need to keep track of the current DataRow and n copy to not repeat the same code for the same row and copy when you set e.HasMorePages = true;. For the copies, request a new page if the bottom of the current output block exceeds the e.MarginBounds.Bottom. To request a new page for each row, uncomment the last lines of the following example.
// +
using System.Drawing.Printing;
// ...
private int curRow = 0;
private int curCopy = 0;
// Or from where you call `.Print();`
// Button.Click event for example.
private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
{
curRow = 0;
curCopy = 0;
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
var curY = e.MarginBounds.Y;
using (var fontNormal = new Font("Arial", 12))
using (var sf = new StringFormat())
{
sf.Alignment = sf.LineAlignment = StringAlignment.Center;
int itemHeight = (int)fontNormal.GetHeight(e.Graphics) + 10;
for (int row = curRow; row < dt.Rows.Count; row++)
{
DataRow dr = dt.Rows[row];
if (!string.IsNullOrEmpty(dr.Field<string>(1)) &&
int.TryParse(dr.Field<string>(4)?.ToString(), out int copies))
{
for (int i = curCopy; i < copies; i++)
{
var imgRect = new Rectangle(e.MarginBounds.X, curY, 200, 200);
var labelRect = new Rectangle(
imgRect.X,
imgRect.Bottom,
imgRect.Width,
itemHeight);
if (curY + imgRect.Height + labelRect.Height >= e.MarginBounds.Bottom)
{
curCopy = i;
e.HasMorePages = true;
return;
}
using (var qrImage = GenerateQRCODE(dr[1].ToString()))
e.Graphics.DrawImage(qrImage, imgRect);
e.Graphics.DrawString(dr[1].ToString(),
fontNormal, Brushes.Black,
labelRect, sf);
curY = labelRect.Bottom + 30;
}
}
curRow = row + 1;
curCopy = 0;
// Uncomment if you want to start a new
// page for each row.
//if (row < dt.Rows.Count - 1)
//{
// e.HasMorePages = true;
// break;
//}
}
}

How to delete image created with code and how to interact with it at all

I am working on a game. For this game i create around 200 images in a box 20x10.
My problem is that pressing 1 button creates them a lot of times which garbages the Memory, which i want to avoid. So i created a little if/else function which is supposed to check wether the images were created or not. In case they weren't, code creates them, but if they were, the code should delete them, and i have no idea how to delete code generated images or how to interract with them at all.
public void GameStart(bool load = false)
{
Random rnd = new Random();
Pause.IsEnabled = true;
Save.IsEnabled = true;
Shuffle.IsEnabled = true;
byte datasave = 0;
int[,] TileID = new int[20,10];
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 10; j++)
{
if(TileID[i,j] != 0)
{
datasave = 1;
}
TileID[i, j] = rnd.Next(1,9);
CreateImage(i, j, TileID[i,j], datasave);
}
}
}
public void CreateImage(int a, int b, int TileID, byte datainfo)
{
if(datainfo != 0)
{
Image image = new Image();
image.Width = 40;
image.Height = 40;
image.Name = $"Tile{a}{b}";
image.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
image.VerticalAlignment = System.Windows.VerticalAlignment.Center;
image.Margin = new Thickness(-1000 + 80 * a, -200 + 80 * b, 0, 0);
string way = #"C:\Users\ignat\Desktop\Игра\Images\";
image.Source = new BitmapImage(new Uri(way + $"icon{TileID}.jpg", UriKind.Absolute));
Grid.Children.Add(image);
}
else
{
CreateImage(a, b, TileID, datainfo);
}

merging columns in datagridview in c#

i have a datagridview on my c# winforms and i want to merge some columns to enter data on it. how will i do that?
i tried some codes from the the net but there are errors and it says: No overload for datagridviewCellPainting that matches the delegate for event handler.
this is my code:
private void General_Inventory_Load(object sender, EventArgs e)
{
dgvGenInventory.Columns.Add("JanWin", "Win");
dgvGenInventory.Columns.Add("JanLoss", "Loss");
dgvGenInventory.Columns.Add("FebWin", "Win");
dgvGenInventory.Columns.Add("FebLoss", "Loss");
dgvGenInventory.Columns.Add("MarWin", "Win");
dgvGenInventory.Columns.Add("MarLoss", "Loss");
dgvGenInventory.Columns.Add("AprWin", "Win");
dgvGenInventory.Columns.Add("AprLoss", "Loss");
dgvGenInventory.Rows.Add("1", "2", "3", "2", "2", "2", "4", "2");
for (int i = 0; i < dgvGenInventory.ColumnCount - 1; i++)
{
dgvGenInventory.Columns[i].Width = 45;
}
this.dgvGenInventory.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.dgvGenInventory.ColumnHeadersHeight = this.dgvGenInventory.ColumnHeadersHeight * 2;
this.dgvGenInventory.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
this.dgvGenInventory.CellPainting += new DataGridViewCellPaintingEventHandler(dgvGenInventory_CellPainting);
this.dgvGenInventory.Paint += new PaintEventHandler(dgvGenInventory_Paint);
this.dgvGenInventory.Scroll += new ScrollEventHandler(dgvGenInventory_Scroll);
this.dgvGenInventory.ColumnWidthChanged += new DataGridViewColumnEventHandler(dgvGenInventory_ColumnWidthChanged);
}
private void dgvGenInventory_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex > -1)
{
Rectangle r2 = e.CellBounds;
r2.Y += e.CellBounds.Height / 2;
r2.Height = e.CellBounds.Height / 2;
e.PaintBackground(r2, true);
e.PaintContent(r2);
e.Handled = true;
}
}
I want to see merged columns on my datagridview
I think, it will be better if you merge data in table first and then bind DataGridview to that table.
try this:
private void Form1_Load(object sender, EventArgs e)
{
m_BuildGrid();
}
private void m_BuildGrid()
{
DataGridViewColumn pColumn;
int i, j;
String strTemp;
HMergedCell pCell;
int nOffset;
dataGridView2.Columns.Add(#"colGroup", #"");
dataGridView2.Columns.Add(#"colTask", #"Task");
pColumn = dataGridView2.Columns["colTask"];
pColumn.Frozen = true;
for (i = 0; i < 25; i++)
{
strTemp = "col" + i.ToString();
dataGridView2.Columns.Add(#strTemp, i.ToString());
pColumn = dataGridView2.Columns[strTemp];
pColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
pColumn.Width = 40;
}
dataGridView2.Rows.Add(20);
nOffset = 2;
for (i = 0; i < 3; i++)
{
for (j = nOffset; j < nOffset + 7; j++)
{
dataGridView2.Rows[0].Cells[j] = new HMergedCell();
pCell = (HMergedCell)dataGridView2.Rows[0].Cells[j];
pCell.LeftColumn = nOffset;
pCell.RightColumn = nOffset + 6;
}
nOffset += 7;
}
for (i = 0; i < 20; i++)
for (j = 0; j < 22; j++)
{
dataGridView2.Rows[i].Cells[j].Value = "{" + i.ToString() + "," + j.ToString() + "}";
}
pColumn = null;
}
}
and add this class to your project
public class HMergedCell : DataGridViewTextBoxCell
{
private int m_nLeftColumn = 0;
private int m_nRightColumn = 0;
/// <summary>
/// Column Index of the left-most cell to be merged.
/// This cell controls the merged text.
/// </summary>
public int LeftColumn
{
get
{
return m_nLeftColumn;
}
set
{
m_nLeftColumn = value;
}
}
/// <summary>
/// Column Index of the right-most cell to be merged
/// </summary>
public int RightColumn
{
get
{
return m_nRightColumn;
}
set
{
m_nRightColumn = value;
}
}
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
try
{
int mergeindex = ColumnIndex - m_nLeftColumn;
int i;
int nWidth;
int nWidthLeft;
string strText;
Pen pen = new Pen(Brushes.Black);
// Draw the background
graphics.FillRectangle(new SolidBrush(SystemColors.Control), cellBounds);
// Draw the separator for rows
graphics.DrawLine(new Pen(new SolidBrush(SystemColors.ControlDark)), cellBounds.Left, cellBounds.Bottom - 1, cellBounds.Right, cellBounds.Bottom - 1);
// Draw the right vertical line for the cell
if (ColumnIndex == m_nRightColumn)
graphics.DrawLine(new Pen(new SolidBrush(SystemColors.ControlDark)), cellBounds.Right - 1, cellBounds.Top, cellBounds.Right - 1, cellBounds.Bottom);
// Draw the text
RectangleF rectDest = RectangleF.Empty;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
sf.Trimming = StringTrimming.EllipsisCharacter;
// Determine the total width of the merged cell
nWidth = 0;
for (i = m_nLeftColumn; i <= m_nRightColumn; i++)
nWidth += this.OwningRow.Cells[i].Size.Width;
// Determine the width before the current cell.
nWidthLeft = 0;
for (i = m_nLeftColumn; i < ColumnIndex; i++)
nWidthLeft += this.OwningRow.Cells[i].Size.Width;
// Retrieve the text to be displayed
strText = this.OwningRow.Cells[m_nLeftColumn].Value.ToString();
rectDest = new RectangleF(cellBounds.Left - nWidthLeft, cellBounds.Top, nWidth, cellBounds.Height);
graphics.DrawString(strText, new Font("Arial", 10, FontStyle.Regular), Brushes.Black, rectDest, sf);
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
}
}
}
I spent a long time looking for this as my boss didn't want to buy any off-the-shelf components. This should be submitted into the .NET code: datagridvewtextboxcell-with-span-behaviour It just works and is soo simple to use. Works with VB/C# .NET 4.5 to 6. Spans rows and columns including headers.
DataGridView.Columns.Add(new DataGridViewTextBoxColumnEx());
var dataGridViewCell = (DataGridViewTextBoxCellEx)DataGridView[colIdx, rowIdx];
dataGridViewCell.ColSpan = 2;
dataGridViewCell.RowSpan = 6;

creating a tablelayoutpanel of pictureboxes takes a long time

I'm creating this tablelayoutpanel of picture boxes (66x66 pixels) and while on one PC it is taking less then a second to finish, it takes about 8 seconds on another pc (with the same capabilities...).
I have to create the graphics on run time as I know only on run time which images I need to place.
This is the function:
private void InitializeDrawerCells(int cabinetPartID, int drawerID)
{
PictureBox pb;
try
{
tblDrawerCells.RowStyles.Clear();
tblDrawerCells.ColumnStyles.Clear();
tblDrawerCells.Controls.Clear();
tblDrawerCells.RowCount = 12;
tblDrawerCells.ColumnCount = 16;
for (int i = 0; i < tblDrawerCells.RowCount; i++)
{
RowStyle style = new RowStyle
{
SizeType = SizeType.Absolute,
Height = tblDrawerCells.Height / tblDrawerCells.RowCount
};
tblDrawerCells.RowStyles.Add(style);
}
for (int i = 0; i < tblDrawerCells.ColumnCount; i++)
{
ColumnStyle style = new ColumnStyle
{
SizeType = SizeType.Absolute,
Width = tblDrawerCells.Width / tblDrawerCells.ColumnCount
};
tblDrawerCells.ColumnStyles.Add(style);
}
for (int i = 0; i < tblDrawerCells.ColumnCount; i++)
{
for (int j = 0; j < tblDrawerCells.RowCount; j++)
{
pb = new PictureBox();
if (_DrawerType == eDrawerType.Regular)
{
if (Scenraio == OpenCabinetScenario.Maintenance)
{
if (NarcoticsCabinetManager.CabinetParts[_CurrentCabPartID].Drawers[_DrawerNumber - 1].DrawerType == eDrawerType.Regular)
pb.BackgroundImage = ImageOn[tblDrawerCells.RowCount - j - 1][i];
else
pb.BackgroundImage = ImageReturnOff;
}
else
pb.BackgroundImage = ImageOff;
}
else
pb.BackgroundImage = global::NarcoticsStorageSystem2.Properties.Resources._11x6_Cells;
pb.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
// pb.Dock = System.Windows.Forms.DockStyle.Fill;
pb.Location = new System.Drawing.Point(0, 0);
pb.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);
if (_DrawerType == eDrawerType.Regular)
pb.Size = new System.Drawing.Size(66, 66);
else if (_DrawerType == eDrawerType.Return)
pb.Size = new System.Drawing.Size(198, 66);
// if (_Scenraio == OpenCabinetScenario.FillItems)
// {
pb.Click += new System.EventHandler(this.pbCell_Click);
// }
pb.TabStop = false;
pb.Tag = new Tuple<int, int, int, int>(_DrawerNumber, tblDrawerCells.RowCount - j, i + 1, (int)ImageType.Off);
tblDrawerCells.Controls.Add(pb, i, j);
}
}
}
catch (Exception ex)
{
//add ex to log...
}
finally
{
}
}
Any ideas?

Get real time input from programmatically generated elements in C# form

How to get value of checkboxes (and the textbox upon change in text) in real time with form particulars that are all generated via code?
This following code produces a form upon button press, the form has checkboxes and a richtextbox. Ideally I want any interaction to have an effect, so if I paste in a grid of ones and zeros the checkboxes update, and once a checkbox gets click, the corresponding one or zero in the textarea will update (So that I can then copy the grid (matrix) out and into another program.
I know how to get the events using the visual studio GUI maker, but not from a programmatically created form like this.
private void begin_button_Click(object sender, EventArgs e)
{
// Build the child form
Form check_box = new Form();
check_box.FormBorderStyle = FormBorderStyle.FixedSingle;
// Get the values from the textboxes
int height = Convert.ToInt16(this.height_input.Text);
int width = Convert.ToInt16(this.width_input.Text);
// Set the dimensions of the form
check_box.Width = width * 15 + 40;
check_box.Height = ( height * 15 + 40 ) * 3;
// Build checkboxes for the checkbox form
CheckBox[] chk;
chk = new CheckBox[height * width];
int count = 0;
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++)
{
chk[count] = new CheckBox();
chk[count].Name = count.ToString();
chk[count].Width = 15; // because the default is 100px for text
chk[count].Height = 15;
chk[count].Location = new Point(j * 15, i * 15);
chk[count].CheckedChanged += new EventHandler(this.CheckedChanged);
check_box.Controls.Add(chk[count]);
count += 1;
//Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count);
}
}
RichTextBox output_area;
output_area = new RichTextBox();
output_area.Location = new Point(chk[0].Location.X, chk[count-1].Location.Y + 30);
check_box.Controls.Add(output_area);
output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!";
output_area.Width = check_box.Width - 40;
output_area.Height = check_box.Height / 2;
// Run the form
check_box.ShowDialog();
}
EDIT:
I have added the event handler and it's working, however I can't access the checkbox form, only the main form.
private void CheckedChanged(object sender, EventArgs e)
{
//throw new NotImplementedException();
CheckBox x = (CheckBox)sender;
Console.WriteLine(x);
Console.WriteLine(x.Name.ToString());
}
Have a look at the .Designer file that the form designer generates for you!
Anyway, in your loop, try something like this:
chk[count].CheckedChanged += MyFancyHandler;
And the handler itself will look just like a normal handler:
private void MyFancyHandler( object sender, EventArgs e )
{
// ...
}
Also notice that the sender argument there will contain a reference to whichever checkbox/control the event refers to.
Below code updates matrix text in the rich text box when check box check state changed.
RichTextBox output_area;
CheckBox[] chk;
Size MatrixSize;
private void begin_button_Click()
{
// Build the child form
Form check_box = new Form();
check_box.FormBorderStyle = FormBorderStyle.FixedSingle;
check_box.StartPosition = FormStartPosition.CenterScreen;
// Get the values from the textboxes
int height = Convert.ToInt16("10");
int width = Convert.ToInt16("7");
MatrixSize = new Size(width, height);
// Set the dimensions of the form
check_box.Width = width * 15 + 40;
check_box.Height = (height * 15 + 40) * 3;
// Build checkboxes for the checkbox form
chk = new CheckBox[height * width];
int count = 0;
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++)
{
chk[count] = new CheckBox();
chk[count].Name = count.ToString();
chk[count].Width = 15; // because the default is 100px for text
chk[count].Height = 15;
chk[count].Location = new Point(j * 15, i * 15);
check_box.Controls.Add(chk[count]);
chk[count].CheckedChanged += new EventHandler(CheckBox1_CheckedChanged);
count += 1;
//Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count);
}
}
output_area = new RichTextBox();
output_area.Location = new Point(chk[0].Location.X, chk[count - 1].Location.Y + 30);
check_box.Controls.Add(output_area);
output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!";
output_area.Width = check_box.Width - 40;
output_area.Height = check_box.Height / 2;
// Run the form
check_box.ShowDialog();
}
private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
Debug.WriteLine(c.Name);
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 1; i <= MatrixSize.Height; i++)
{
for (int j = 1; j <= MatrixSize.Width; j++)
{
if (chk[count].Checked)
{
sb.Append("1,");
}
else
{
sb.Append("0,");
}
count += 1;
}
sb.Append("\r\n");
}
output_area.Text = sb.ToString();
}

Categories