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;
Related
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;
//}
}
}
I am currently trying to develop a form of battleships on c# windows form.
Here is the code I am trying to use.. the trouble I have been having is how to create a second set of buttons (another 10x10) behind the other, with two sets of controls so I can switch between the two.
I have everything like AI and automated setups, I just need to have 2 button controls. I hope someone can help me out with this! Many thanks!
private List<List<Button>> grid = new List<List<Button>>();
public UserForm()
{
InitializeComponent();
byte numRows = 10;
byte numCols = 10;
for (byte i = 0; i < numRows; i++)
{
grid.Add(ButtonRowCreator(numCols, 25, (i+1) * 50));
}
}
public List<Button> ButtonRowCreator(byte numOfBtnsNeeded, int x, int y)
{
List<Button> btns = new List<Button>();
for (int i = 0; i < numOfBtnsNeeded; i++)
{
Button btn = new Button();
btn.Size = new Size(50, 50);
btn.Location = new Point(x + (i * btn.Width), y);
btns.Add(btn);
btn.Font = new Font("Georiga", 10);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
return btns;
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
int curRow = -1, curCol = -1;
for(int i = 0; i < grid.Count; i++)
{
int index = grid[i].IndexOf(btn);
if (index != -1)
{
curRow = i;
curCol = index;
Console.WriteLine("curRow = " + curRow.ToString() + ", curCol = " + curCol.ToString());
}
}
// ... now you can use "curRow", "curCol" and "grid" to do something ...
foreach (List<Button> row in grid)
{
foreach (Button col in row)
{
col.ForeColor = Color.Gray;
}
}
if (board[curRow, curCol] == 1)
{
if (btn.Text == "Hit")
{
}
else
{
btn.Text = "Hit";
btn.BackColor = Color.Red;
hit++;
}
if (hit == 17)
{
MessageBox.Show("Congratulations, You Sunk Their Battleships!");
MessageBox.Show("Thanks For Playing!");
MessageBox.Show("Goodbye!");
}
}
else
{
btn.Text = "Miss!";
btn.BackColor = Color.Blue;
}
I think this is what you're after?
It looks like a lot of your code is used to figure out what button is clicked on. This information can be stored on the button object itself in the Tag property and greatly simplifies the code.
private Button[,] _grid1;
private Button[,] _grid2;
public UserForm()
{
InitializeComponent();
_grid1 = new Button[10, 10];
_grid2 = new Button[10, 10];
CreateGrid(_grid1, 10, 10, 25, 0, 20, true);
CreateGrid(_grid2, 10, 10, 25, 250, 20, false);
}
public void CreateGrid(Button[,] grid, int numOfRows, int numOfCols, int offsetX, int offsetY, int buttonSize, bool enabled)
{
for (byte i = 0; i < numOfRows; i++)
{
for (byte j = 0; j < numOfCols; j++)
{
grid[i,j] = ButtonCreator(i, j, offsetX, offsetY, buttonSize, enabled);
}
}
}
public Button ButtonCreator(int row, int col, int x, int y, int buttonSize, bool enabled)
{
Button btn = new Button();
btn.Size = new Size(buttonSize, buttonSize);
btn.Location = new Point(x + (col * buttonSize), y + (row * buttonSize));
btn.Font = new Font("Georiga", 10);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
btn.Tag = row + "," + col;
btn.Enabled = enabled;
return btn;
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string[] coord = btn.Tag.ToString().Split(',');
int curRow = Convert.ToInt32(coord[0]);
int curCol = Convert.ToInt32(coord[1]);
Console.WriteLine(curRow = " + curRow + ", curCol = " + curCol);
// ... now you can use "curRow", "curCol" to do something ...
_grid1[curRow, curCol].BackColor = Color.Red;
}
I am doing a program with Emgu.CV in C#
and i receive this error when compiling
An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in InAirSignature.exe
Additional information: Could not load file or assembly 'Emgu.CV.UI,
Version=2.9.0.1922, Culture=neutral, PublicKeyToken=7281126722ab4438'
or one of its dependencies. The system cannot find the file specified.
any ideas how to solve?
for my coding, a webcam is needed.
below is my coding.
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 Emgu.CV;
using Emgu.CV.GPU;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;
using Emgu.CV.ML.Structure;
using Emgu.CV.ML;
using System.IO;
namespace InAirSignature
{
public partial class Main : Form
{
private Capture capture;
private Rectangle roi;
private Bgr redOrGreen;
private const int NUMBERS_OF_FRAMES = 90,
NUMBERS_OF_SIGN = 6,
NUMBERS_OF_FEATURES = 3, // X Y Averange
FEATURE_X = 0,
FEATURE_Y = 1,
TEST = NUMBERS_OF_SIGN - 1,
NUMBERS_OF_NEURONS = 15;
private const int frameHeight = 640;
private const int frameWidth = 480;
private List<Image<Gray, Byte>> imgGrayBuffer = new List<Image<Gray, Byte>>();
private List<int> pointX = new List<int>();
private List<int> pointY = new List<int>();
private int[][][] pointsOfSign, distanceBetweenPoints;
private double[] finalAverage;
private int[][] pointsOfSignReference;
private int[] distanceBetweenPointsForRefenceAndTest;
private int[] classes = {0,0,0,0,1,1,1,1,1,1};
private int resultMode = 0;
private int recordSign = 0;
private bool record = false;
private int counter = 0;
private Stopwatch stopWatch;
private const string SYSTEM_MESSAGE = "System Message: ",
WELCOME_MESSAGE = "Welcome! ";
Matrix<int> layerSize;
MCvANN_MLP_TrainParams parameters;
ANN_MLP network;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Form /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Form
public Main()
{
InitializeComponent();
#region Initialize graph
chartX.Series.Add("X1");
chartX.Series.Add("X2");
chartX.Series.Add("X3");
chartX.Series.Add("X4");
chartX.Series.Add("X5");
chartX.Series.Add("Xtest");
chartX.Series.Add("Xref");
chartY.Series.Add("Y1");
chartY.Series.Add("Y2");
chartY.Series.Add("Y3");
chartY.Series.Add("Y4");
chartY.Series.Add("Y5");
chartY.Series.Add("Ytest");
chartY.Series.Add("Yref");
chartX.Series["X1"].Color = Color.Blue;
chartX.Series["X2"].Color = Color.Green;
chartX.Series["X3"].Color = Color.Red;
chartX.Series["X4"].Color = Color.Pink;
chartX.Series["X5"].Color = Color.Purple;
chartX.Series["Xtest"].Color = Color.Aqua;
chartX.Series["Xref"].Color = Color.BlueViolet;
chartY.Series["Y1"].Color = Color.Blue;
chartY.Series["Y2"].Color = Color.Green;
chartY.Series["Y3"].Color = Color.Red;
chartY.Series["Y4"].Color = Color.Pink;
chartY.Series["Y5"].Color = Color.Purple;
chartY.Series["Ytest"].Color = Color.Aqua;
chartY.Series["Yref"].Color = Color.BlueViolet;
chartX.Series["X1"].ChartType = SeriesChartType.FastLine;
chartX.Series["X2"].ChartType = SeriesChartType.FastLine;
chartX.Series["X3"].ChartType = SeriesChartType.FastLine;
chartX.Series["X4"].ChartType = SeriesChartType.FastLine;
chartX.Series["X5"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xtest"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xref"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y1"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y2"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y3"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y4"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y5"].ChartType = SeriesChartType.FastLine;
chartY.Series["Ytest"].ChartType = SeriesChartType.FastLine;
chartY.Series["Yref"].ChartType = SeriesChartType.FastLine;
#endregion
#region Initialize Neural Network
layerSize = new Matrix<int>(new int[] { NUMBERS_OF_FEATURES, NUMBERS_OF_NEURONS, 1 });
parameters = new MCvANN_MLP_TrainParams();
parameters.term_crit = new MCvTermCriteria(10, 1.0e-8);
parameters.train_method = Emgu.CV.ML.MlEnum.ANN_MLP_TRAIN_METHOD.BACKPROP;
parameters.bp_dw_scale = 0.1;
parameters.bp_moment_scale = 0.1;
network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
#endregion
#region Initialize camera
capture = new Capture();
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, frameHeight);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, frameWidth);
#endregion
initializeData();
roi = new Rectangle(338, 2, 300, 300);
redOrGreen = new Bgr(Color.Red);
lblSM.Text = SYSTEM_MESSAGE + WELCOME_MESSAGE;
updateResult();
updateGraph();
Application.Idle += processFrame;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Button
private void btnSign_Click(object sender, EventArgs e)
{
stopWatch = Stopwatch.StartNew();
record = true;
redOrGreen = new Bgr(Color.LightGreen);
if (sender == btnSign1)
recordSign = 1;
else if (sender == btnSign2)
recordSign = 2;
else if (sender == btnSign3)
recordSign = 3;
else if (sender == btnSign4)
recordSign = 4;
else if (sender == btnSign5)
recordSign = 5;
else
recordSign = 6;
}
private void btnPredict_Click(object sender, EventArgs e)
{
float predicted = predict(new int[,] { { distanceBetweenPointsForRefenceAndTest[0], distanceBetweenPointsForRefenceAndTest[1], distanceBetweenPointsForRefenceAndTest[2] } }, network);
string result;
if (predicted < Convert.ToDouble(lblThreshold.Text))
result = "Success";
else
result = "Fail";
lblSM.Text = SYSTEM_MESSAGE + "Matching result - " + result + ", value: " + predicted.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
saveSignReference();
network.Save(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Saved";
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "ID blank";
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
loadSignReference();
network.Load(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Loaded";
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
updateGraph();
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "Invalid ID";
}
}
private void btnTrainNN_Click(object sender, EventArgs e)
{
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
trainNN();
}
private void btnClear_Click(object sender, EventArgs e)
{
initializeData();
updateGraph();
updateResult();
calculateResult();
rbS1.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Check Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Check Box
private void cbBinaryImage_CheckedChanged(object sender, EventArgs e)
{
ibBinaryImage.Visible = !ibBinaryImage.Visible;
}
private void cbResult_CheckedChanged(object sender, EventArgs e)
{
pnlResult.Visible = !pnlResult.Visible;
}
private void cbSign_CheckedChanged(object sender, EventArgs e)
{
if (sender == cbSign1)
{
chartX.Series["X1"].Enabled = !chartX.Series["X1"].Enabled;
chartY.Series["Y1"].Enabled = !chartY.Series["Y1"].Enabled;
}
else if (sender == cbSign2)
{
chartX.Series["X2"].Enabled = !chartX.Series["X2"].Enabled;
chartY.Series["Y2"].Enabled = !chartY.Series["Y2"].Enabled;
}
else if (sender == cbSign3)
{
chartX.Series["X3"].Enabled = !chartX.Series["X3"].Enabled;
chartY.Series["Y3"].Enabled = !chartY.Series["Y3"].Enabled;
}
else if (sender == cbSign4)
{
chartX.Series["X4"].Enabled = !chartX.Series["X4"].Enabled;
chartY.Series["Y4"].Enabled = !chartY.Series["Y4"].Enabled;
}
else if (sender == cbSign5)
{
chartX.Series["X5"].Enabled = !chartX.Series["X5"].Enabled;
chartY.Series["Y5"].Enabled = !chartY.Series["Y5"].Enabled;
}
else if (sender == cbSignRefer)
{
chartX.Series["Xref"].Enabled = !chartX.Series["Xref"].Enabled;
chartY.Series["Yref"].Enabled = !chartY.Series["Yref"].Enabled;
}
else
{
chartX.Series["Xtest"].Enabled = !chartX.Series["Xtest"].Enabled;
chartY.Series["Ytest"].Enabled = !chartY.Series["Ytest"].Enabled;
}
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Radio Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Radio Button
private void rbS_CheckedChanged(object sender, EventArgs e)
{
if (sender == rbS1)
resultMode = 0;
else if (sender == rbS2)
resultMode = 1;
else if (sender == rbS3)
resultMode = 2;
else if (sender == rbS4)
resultMode = 3;
else
resultMode = 4;
updateResult();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Text Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Text Box
private void tbId_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnLoad.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Function /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private void processFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> frame = capture.QueryFrame().Flip(FLIP.HORIZONTAL);
Image<Bgr, Byte> frameCrop = frame.Copy(new Rectangle(338, 2, 300, 300)); // copy a crop
Image<Gray, Byte> frameBinary;
if (counter == (NUMBERS_OF_FRAMES - 2))
redOrGreen = new Bgr(Color.Red);
frame.Draw(roi, redOrGreen, 2);
frameBinary = ImageProcessing.getSkin(frameCrop);
if (record == true)
{
imgGrayBuffer.Add(frameBinary);
counter++;
if (counter == NUMBERS_OF_FRAMES)
{
while (imgGrayBuffer.Count() > 0)
{
Point point = ImageProcessing.getHighestPoint(imgGrayBuffer.ElementAt(0));
imgGrayBuffer.RemoveAt(0);
pointX.Add(point.X);
pointY.Add(point.Y);
}
pointsOfSign[recordSign - 1][FEATURE_X] = pointX.ToArray();
pointsOfSign[recordSign - 1][FEATURE_X] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_X] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_Y] = pointY.ToArray();
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointX.Clear();
pointY.Clear();
calculateResult();
updateResult();
updateGraph();
record = false;
stopWatch.Stop();
lblSM.Text = SYSTEM_MESSAGE + "Time taken => " + stopWatch.Elapsed.TotalSeconds.ToString() + " seconds.";
if (cbAuto.Checked == true && recordSign == 6)
btnVerify.PerformClick();
recordSign = 0;
counter = 0;
}
}
ibMain.Image = frame;
if(cbBinaryImage.Checked == true)
ibBinaryImage.Image = frameBinary;
}
private int[] normalizePosition(int[] position)
{
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int midPoint = (min + max) / 2;
for (int i = 0; i < position.Count(); i++)
position[i] -= midPoint;
return position;
}
private int[] normalizeSize(int[] position)
{
const int targetSize = 300;
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int height = max - min;
if (height != 0)
height = targetSize / height;
for (int i = 0; i < position.Count(); i++)
position[i] *= height;
return position;
}
private void updateGraph()
{
foreach (var series in chartX.Series)
series.Points.Clear();
foreach (var series in chartY.Series)
series.Points.Clear();
for (int i = 0; i < NUMBERS_OF_FRAMES; i++)
{
chartX.Series["X1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_X][i]);
chartX.Series["X2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_X][i]);
chartX.Series["X3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_X][i]);
chartX.Series["X4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_X][i]);
chartX.Series["X5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_X][i]);
chartX.Series["Xref"].Points.AddXY
(i, pointsOfSignReference[0][i]);
chartX.Series["Xtest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_X][i]);
chartY.Series["Y1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_Y][i]);
chartY.Series["Y2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_Y][i]);
chartY.Series["Y3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_Y][i]);
chartY.Series["Y4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_Y][i]);
chartY.Series["Y5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_Y][i]);
chartY.Series["Yref"].Points.AddXY
(i, pointsOfSignReference[1][i]);
chartY.Series["Ytest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_Y][i]);
}
}
private void calculateResult()
{
int average = 0;
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
for (int j = 0; j < NUMBERS_OF_SIGN - 1; j++)
{
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPoints[i][j][k] = DTW.Distance(pointsOfSign[i][k], pointsOfSign[j][k]);
average += distanceBetweenPoints[i][j][k];
}
distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1] = average / 2;
average = 0;
}
for (int i = 0; i < NUMBERS_OF_SIGN -1; i++)
{
finalAverage[i] = 0.0;
for (int j = 0; j < NUMBERS_OF_SIGN; j++)
finalAverage[i] += distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1];
finalAverage[i] /= NUMBERS_OF_SIGN - 2;
}
average = 0;
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPointsForRefenceAndTest[k] = DTW.Distance(pointsOfSignReference[k], pointsOfSign[TEST][k]);
average += distanceBetweenPointsForRefenceAndTest[k];
}
distanceBetweenPointsForRefenceAndTest[NUMBERS_OF_FEATURES - 1] = average / 2;
}
private void updateResult()
{
tbResult1X.Text = distanceBetweenPoints[resultMode][0][0].ToString();
tbResult1Y.Text = distanceBetweenPoints[resultMode][0][1].ToString();
tbResult1A.Text = distanceBetweenPoints[resultMode][0][2].ToString();
tbResult2X.Text = distanceBetweenPoints[resultMode][1][0].ToString();
tbResult2Y.Text = distanceBetweenPoints[resultMode][1][1].ToString();
tbResult2A.Text = distanceBetweenPoints[resultMode][1][2].ToString();
tbResult3X.Text = distanceBetweenPoints[resultMode][2][0].ToString();
tbResult3Y.Text = distanceBetweenPoints[resultMode][2][1].ToString();
tbResult3A.Text = distanceBetweenPoints[resultMode][2][2].ToString();
tbResult4X.Text = distanceBetweenPoints[resultMode][3][0].ToString();
tbResult4Y.Text = distanceBetweenPoints[resultMode][3][1].ToString();
tbResult4A.Text = distanceBetweenPoints[resultMode][3][2].ToString();
tbResult5X.Text = distanceBetweenPoints[resultMode][4][0].ToString();
tbResult5Y.Text = distanceBetweenPoints[resultMode][4][1].ToString();
tbResult5A.Text = distanceBetweenPoints[resultMode][4][2].ToString();
tbTotalA.Text = finalAverage[resultMode].ToString();
tbRatX.Text = distanceBetweenPointsForRefenceAndTest[0].ToString();
tbRatY.Text = distanceBetweenPointsForRefenceAndTest[1].ToString();
tbRatA.Text = distanceBetweenPointsForRefenceAndTest[2].ToString();
}
private float predict(int[,] testingSetInt, ANN_MLP network)
{
Matrix<float> testingSet = new Matrix<float>(Utility.arrayIntToFloat(testingSetInt)),
prediction = new Matrix<float>(1, 1);
network.Predict(testingSet, prediction);
return prediction.Data[0, 0];
}
private ANN_MLP trainNN(int[] trainingClassesInt, int[,] trainingSetInt)
{
int numbers_of_training_set = 4,
numbers_of_data = trainingSetInt.GetUpperBound(0) + 1;
Matrix<float> trainingSet = new Matrix<float>(Utility.arrayIntToFloat(trainingSetInt)),
trainingClasses = new Matrix<float>(Utility.arrayIntToFloat(trainingClassesInt));
Matrix<float> trainingSetPositive = trainingSet.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainingSetNegative = trainingSet.GetRows(numbers_of_training_set, numbers_of_data, 1);
Matrix<float> trainClassesPositive = trainingClasses.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainClassesNegative = trainingClasses.GetRows(numbers_of_training_set, numbers_of_data, 1);
ANN_MLP network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
network.Train(trainingSet, trainingClasses, null, (Matrix<int>)null, parameters, Emgu.CV.ML.MlEnum.ANN_MLP_TRAINING_FLAG.DEFAULT);
return network;
}
private void trainNN()
{
// Getting the most closest signature
int index = 0;
for (int i = 1; i < NUMBERS_OF_SIGN - 1; i++)
if (finalAverage[index] > finalAverage[i])
index = i;
lblSM.Text = SYSTEM_MESSAGE + "Sign # no." + (index + 1).ToString() + " is the reference now!";
for (int i = 0; i < NUMBERS_OF_FEATURES - 1; i++)
pointsOfSignReference[i] = pointsOfSign[index][i];
int total_training_data = 10; // 4 positive, 6 negative
int total_features_for_training = 3; // dtw of x, dtw of y, width of sign
int[,] trainingSet = new int[total_training_data, total_features_for_training];
// Get the distance (x and y) between closest signature and the rest of signature into training set
// Feature 0 and 1 => dtw of x, dtw of y
for (int i = 0, current = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
if (i != index)
{
for (int j = 0; j < NUMBERS_OF_FEATURES; j++)
trainingSet[current, j] = distanceBetweenPoints[i][index][j];
current++;
}
}
// Generate negative data
int[] max_value = new int[NUMBERS_OF_FEATURES];
int[] min_value = new int[NUMBERS_OF_FEATURES];
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
for (int j = 0; j < NUMBERS_OF_FEATURES && i != index; j++)
{
if (max_value[j] < distanceBetweenPoints[i][index][j])
max_value[j] = distanceBetweenPoints[i][index][j];
if (min_value[j] > distanceBetweenPoints[i][index][j])
min_value[j] = distanceBetweenPoints[i][index][j];
}
}
Random random = new Random();
In your project, right click on the References, then look for the Emgu.CV.UI assembly and select it.
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.
I have a small program that generates a few dynamic labels in a flowLayoutPanel1 I ma trying to export these labels' text to Excel but all I get is the value of the last label.
This is my Export class:
class Export
{
public Export(bool defaultBackgroundIsWhite)
{
this.defaultBackgroundIsWhite = defaultBackgroundIsWhite;
app = new Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Worksheet)workbook.Sheets[1];
}
public void Do(string excelName, System.Windows.Forms.Label names)
{
for (int i = 0; i <= 5; i++)
{
AddNames(i,0,names);
}
}
private void AddNames(int row, int col, System.Windows.Forms.Label lbls)
{
if (lbls == null) return;
row++;
col++;
Range range = worksheet.Cells[row + 2, col + 2];
range.NumberFormat = "";
worksheet.Cells[row + 2, col + 2] = lbls.Text;
row--;
col--;
}
private Application app = null;
private Workbook workbook = null;
private Worksheet worksheet = null;
private bool defaultBackgroundIsWhite;
}
The form class code:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
create();
}
Label lbl;
private void create()
{
flowLayoutPanel1.Controls.Clear();
//int length = ds.Tables[0].Rows.Count;
for (int i = 0; i < 5; i++)
{
lbl = new Label();
lbl.Name = i.ToString();
lbl.Text = "Label "+i;
lbl.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
lbl.SetBounds(0, 20, 100, 25);
lbl.BorderStyle = BorderStyle.FixedSingle;
flowLayoutPanel1.Controls.Add(lbl);
}
}
private void button1_Click(object sender, EventArgs e)
{
Export ep = new Export(true);
ep.Do("test.xsl", lbl);
}
My Results:
You are always adding the text of the last created label because you are only passing its reference. You should instead pass the List with references of all the labels which Text properties you would like to export to Excel. Change these methods:
List<Label> lbls;
private void create()
{
flowLayoutPanel1.Controls.Clear();
//int length = ds.Tables[0].Rows.Count;
lbls = new List<Labels>();
for (int i = 0; i < 5; i++)
{
Label lbl = new Label();
lbl.Name = i.ToString();
lbl.Text = "Label "+i;
lbl.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
lbl.SetBounds(0, 20, 100, 25);
lbl.BorderStyle = BorderStyle.FixedSingle;
flowLayoutPanel1.Controls.Add(lbl);
lbls.Add(lbl);
}
}
Also change the method Do in the Export class to accept the List<Label> instead Label:
public void Do(string excelName, List<Label> names)
{
for (int i = 0; i <= names.Count; i++)
{
AddNames(i,0,names[i]);
}
}
List<Label> lbls = new List<Label>();
private void create()
{
flowLayoutPanel1.Controls.Clear();
//int length = ds.Tables[0].Rows.Count;
for (int i = 0; i < 5; i++)
{
lbl = new Label();
lbl.Name = i.ToString();
lbl.Text = "Label "+i;
lbl.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
lbl.SetBounds(0, 20, 100, 25);
lbl.BorderStyle = BorderStyle.FixedSingle;
lbls.Add(lbl); //< -- add the label to the local list of Labels
flowLayoutPanel1.Controls.Add(lbl);
}
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
Export ep = new Export(true);
foreach(var lbl in lbls)
{
i++;
ep.AddNames(i,0,lbl);
}
}
public void AddNames(int row, int col, System.Windows.Forms.Label lbl)
{
if (lbl == null) return;
row++;
col++;
Range range = worksheet.Cells[row + 2, col + 2];
range.NumberFormat = "";
worksheet.Cells[row + 2, col + 2] = lbl.Text;
row--;
col--;
}
You're constructing a new label every time around the for loop in the create() method, and assigning that label to the same field (lbl). By the time you're done, lbl is the last label you created. You could instead add the labels to a List, or pass flowLayoutPanel1.Controls to the go() method, if you can be certain that will contain only the labels you wish to export.
It's a bit clunky TBH, and depending so heavily on the mechanics of the UI like that is not recommended - you'd be far better of with a well thought out model to which your UI is data bound, but if you want to just get it done, that's your problem.