How to solve this Call stack on this program - c#

Error: the class choosedisplay can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file.
How to move the class code so that it is in the first class.
I dont Know about program i am a Mechanical Engineer. I trying to do my project in C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GraphSynth.Representation;
using GraphSynth.Forms;
using GraphSynth.Generation;
namespace GraphSynth.Forms
{
public class chooseViaHumanGui : RecognizeChooseApply
{
public override int choose(List<option> options, candidate cand)
{
SearchIO.output("There are " + options.Count.ToString() + " recognized locations.", 2);
if (options.Count == 0)
{
SearchIO.output("Sorry there are no rules recognized.", 0);
return int.MinValue;
}
else if (options.Count > Program.settings.maxRulesToDisplay)
{
SearchIO.output("Sorry there are too many rules to show.", 0);
return int.MinValue;
}
else
{
SearchIO.output("Double-click on one to show the location.", 2);
chooseDisplay choiceDisplay = new chooseDisplay();
choiceDisplay.promptUser(options, (Boolean)(cand.recipe.Count == 0));
return choiceDisplay.choice;
}
}
public override double[] choose(option RC, candidate cand)
{ return null; }
#region Constructors
public chooseViaHumanGui(Boolean _display)
: base(Program.seed, Program.rulesets, Program.settings.maxRulesToApply, _display,
Program.settings.recompileRules, Program.settings.execDir, Program.settings.compiledparamRules) { }
#endregion
}
// This is the class Program for choose display //
public partial class chooseDisplay : Form
{
#region Fields
List<option> rulesToDisplay = new List<option>();
List<int> optionNumbers = new List<int>();
public int choice = int.MinValue;
System.Windows.Forms.Timer checkForStopTimer = new System.Windows.Forms.Timer();
#endregion
public chooseDisplay()
{
checkForStopTimer.Tick += new EventHandler(processTimer_Tick);
checkForStopTimer.Interval = 500;
checkForStopTimer.Start();
}
public void promptUser(List<option> RCs, Boolean hideUndo)
{
InitializeComponent();
rulesToDisplay = RCs;
string ruleNo, location;
int option = 0;
this.Text = "Choices from RuleSet #" + RCs[0].ruleSetIndex.ToString();
for (int i = 0; i != rulesToDisplay.Count; i++)
{
option = i + 1;
ruleNo = rulesToDisplay[i].ruleNumber.ToString();
location = rulesToDisplay[i].location.ToString();
recognizedRulesList.Items.Add(option.ToString() + ".\t" + ruleNo + "\t" + location);
optionNumbers.Add(i);
}
if (hideUndo) this.undoButton.Enabled = false;
ShowDialog();
}
private void showGraph_Click(object sender, EventArgs e)
{
SearchIO.addAndShowGraphDisplay(rulesToDisplay[recognizedRulesList.SelectedIndex].location.copy(),
"Recognized Location " + recognizedRulesList.SelectedItem.ToString());
}
private void removeFromList_Click(object sender, EventArgs e)
{
int numToRemove = recognizedRulesList.CheckedIndices.Count;
if (numToRemove == recognizedRulesList.Items.Count)
{
MessageBox.Show("You cannot remove all possible options.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (numToRemove == recognizedRulesList.Items.Count - 1)
{
int[] toRemove = new int[numToRemove];
recognizedRulesList.CheckedIndices.CopyTo(toRemove, 0);
for (int i = numToRemove; i != 0; i--)
{
if (toRemove[i - 1] != optionNumbers.Count)
{
recognizedRulesList.Items.RemoveAt(toRemove[i - 1]);
optionNumbers.RemoveAt(toRemove[i - 1]);
}
}
if (DialogResult.Yes == MessageBox.Show(
"You are removing all but one option [" +
recognizedRulesList.Items[0].ToString() +
"]. Would you like to apply this option?",
"Apply Remaining Option?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
choice = optionNumbers[0];
this.Close();
}
}
else
{
int[] toRemove = new int[numToRemove];
recognizedRulesList.CheckedIndices.CopyTo(toRemove, 0);
for (int i = numToRemove; i != 0; i--)
{
if (toRemove[i - 1] != optionNumbers.Count)
{
recognizedRulesList.Items.RemoveAt(toRemove[i - 1]);
optionNumbers.RemoveAt(toRemove[i - 1]);
}
}
}
}
private void applyButton_Click(object sender, EventArgs e)
{
int numChecked = recognizedRulesList.CheckedIndices.Count;
checkForStopTimer.Stop();
if (numChecked == 0)
{
MessageBox.Show("No Options Checked.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
checkForStopTimer.Start();
}
else if (numChecked == 1)
{
if (!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show(
"Apply Option: " + recognizedRulesList.CheckedItems[0].ToString() + "?",
"Apply Option?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)))
{
int[] toSaveVector = new int[numChecked];
recognizedRulesList.CheckedIndices.CopyTo(toSaveVector, 0);
choice = optionNumbers[toSaveVector[0]];
this.Close();
}
else checkForStopTimer.Start();
}
else if (DialogResult.Yes == MessageBox.Show(
"You cannot apply all of these at the same time. Would you simply like to remove all unchecked Options?", "Remove Unchecked?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
int[] toSaveVector = new int[numChecked];
recognizedRulesList.CheckedIndices.CopyTo(toSaveVector, 0);
List<int> toSave = new List<int>(toSaveVector);
for (int i = recognizedRulesList.Items.Count; i != 0; i--)
{
if (!toSave.Contains(i - 1))
{
recognizedRulesList.Items.RemoveAt(i - 1);
optionNumbers.RemoveAt(i - 1);
}
}
checkForStopTimer.Start();
}
else checkForStopTimer.Start();
}
void processTimer_Tick(object sender, EventArgs e)
{
if (Program.terminateRequest)
{
recognizedRulesList.SetItemChecked(recognizedRulesList.Items.Count - 1, true);
for (int i = 0; i != recognizedRulesList.Items.Count - 1; i++)
recognizedRulesList.SetItemChecked(i, false);
applyButton_Click(sender, e);
}
}
private void undo_Click(object sender, EventArgs e)
{
if ((!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show("Undo the last rule that was applied?",
"Undo Last Rule?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))))
{
choice = -1;
this.Close();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if ((!Program.settings.confirmEachUserChoice ||
(DialogResult.Yes == MessageBox.Show("Send Stop message to Generation Process?",
"Send Stop?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))))
{
choice = int.MinValue;
this.Close();
}
}
}
}

Look here: https://stackoverflow.com/a/8864376/3317555. Basically the choosedisplay class is sharing a file with another class. All you should have to do is move choosedisplay into it's own file.
EDIT: Fixed bad wording.

You've got two classes declared in the same code file. Move the second one to a different file.
EDIT: Actually, as the second is a form and is probably what that code file was created for in the first place, you should probably move the first class out into its own file.

Related

Stopping the calculations because of predicted error

I am unsure how to ask this question as I can't quite well translate it.
I am currently working on my own Windows Form Application that will calculate the dimensions of a given package in inches (written all together in string format) and calculate the dimensions in centimeters, milimeters or even meters and at this point I was wondering what if someone entered wrong dimensions and given measures can not be parsed.
Something like Environment.Exit(), but without closing the application just stopping calculations and writing a message that an error has occured.
If there is a question like this answered, please do link it because I haven't been able to find it.
namespace PretvaranjeDimenzija
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public double mjera = 1;
public bool pogreska = false;
public string mjeraKratica = " cm";
public string dimenzijeIspis = "";
private void buttonIzracunaj_Click(object sender, EventArgs e)
{
string dim = textBoxDimenzije.Text;
if (dim.Contains('.'))
{
dim = dim.Replace('.', ',');
}
if (dim.Length != 0)
{
if (dim.IndexOf('x') != -1)
{
string[] multiDim = dim.Split('x');
double[] multiDimCentimetara = new double[multiDim.Length];
bool[] uspjeh = new bool[multiDim.Length];
for (int i = 0; i < multiDim.Length; i++)
{
uspjeh[i] = double.TryParse(multiDim[i], out multiDimCentimetara[i]);
if (uspjeh[i] == false)
{
pogreska = true;
goto kraj;
}
}
kraj:
if (pogreska == true)
{
MessageBox.Show("Doslo je do pogreske!");
pogreska = false;
}
else
{
double[] dimenzije = new double[multiDim.Length];
for (int i = 0; i < dimenzije.Length; i++)
{
dimenzije[i] = multiDimCentimetara[i] * 2.54 * mjera;
if (i == dimenzije.Length - 1)
{
dimenzijeIspis += dimenzije[i].ToString() + mjeraKratica;
}
else
{
dimenzijeIspis += dimenzije[i].ToString() + "x";
}
}
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
}
else
{
double dimCentimetara;
if(double.TryParse(dim, out dimCentimetara))
{
double dimenzija = dimCentimetara * 2.54 * mjera;
dimenzijeIspis = dimenzija.ToString() + mjeraKratica;
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
else
{
MessageBox.Show("Doslo je do pogreske!");
return;
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
mjera = 0.01;
mjeraKratica = " m";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton1.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton1.Checked = true;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
mjera = 1;
mjeraKratica = " cm";
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton2.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton2.Checked = true;
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
mjera = 10;
mjeraKratica = " mm";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton3.Checked = true;
}
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton3.Checked = true;
}
}
}
It should be pretty simple, depending on your requirements. For example, you could just use a basic if block in your method.
void CalculateStuff()
{
// Get input. Do stuff.
if (IsInvalid)
{
MessageBox.Show("You did a bad thing.");
return; // exit the method.
}
// now that we know the input is good, do other stuff.
}
Substitute IsInvalid with whatever check condition you want that will return true if the input is not valid.

C# bowling calculator. Array of classes returning null

I am working on a project in c# visual studio in which i am attempting to make a bowling calculator. i have made a class for frames which contains a throw1 and throw2. I first fill the array of classes with one button and calculate score after game completion. when i go to calculate score it tells me i have null values.below is my form code the class is just
class frames
{
public int intThrow1;
public int intThrow2;
}
the main form is
public partial class Form1 : Form
{
frames[] frame = new frames[11];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int intFrst = int.Parse(textBox1.Text);
int intScnd = int.Parse(textBox2.Text);
if (lbxScorecard.Items.Count <= 21)
{
int intIndx = 0;
if (intFrst == 10)
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = 0;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx += 2;
}
else
{
frame[intIndx] = new frames();
frame[intIndx].intThrow1 = intFrst;
frame[intIndx].intThrow2 = intScnd;
lbxScorecard.Items.Add(frame[intIndx].intThrow1);
lbxScorecard.Items.Add(frame[intIndx].intThrow2);
intIndx++;
}
}
else
{
MessageBox.Show("max throws");
}
}
private void button2_Click(object sender, EventArgs e)
{
int intScore = 0;
for (int index = 0; index <= 11; index++)
{
if (frame[index].intThrow1 == 10 && index < 9) // here is where it throws a null exception stating the index may be empty
{
if (frame[index + 1].intThrow1 != 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 1].intThrow2;
}
else if (frame[index].intThrow1 == 10)
{
intScore = intScore + frame[index].intThrow1 + frame[index + 1].intThrow1 + frame[index + 2].intThrow1;
}
}
else if (frame[index].intThrow1 + frame[index].intThrow2 == 10 && index < 9) //it was throwing the same exception here until i added && index<9 in the if statements.
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2 + frame[index + 1].intThrow1;
}
else
{
intScore = intScore + frame[index].intThrow1 + frame[index].intThrow2;
}
}
MessageBox.Show(intScore.ToString());
}
}
Problem is:
frames[] frame = new frames[11];
You also need to instantiate each element of the array like you did in the button1_Click function:
frame[intIndx] = new frames();
Also note that you have a class variable frame and the same one in button2_Click which is probably a bad idea.

prevent duplicate entries in C1TrueDBGrid

I am working with my C# Windows application, and this is my first time to use tdbgrid(component1). I want to prevent users from inputting duplicated values after validating them with the database.
Below is the code which I am using for it in (BeforeColUpdate)Event:
bool ExitValue = false;
private void C1TrueDBGrid_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)
{
if (e.Column.Name == "Groups Code")
{
for (int currentRow = 0; currentRow < this.C1TrueDBGrid.Rows.Count - 1;currentRow++)
{
string rowToCompare = this.C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.CellValue(currentRow).ToString();
for (int otherRow = currentRow+1 ; otherRow < this.C1TrueDBGrid.Rows.Count; otherRow++)
{
bool DuplicatedRow = true;
string Row = this.C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.CellValue(otherRow).ToString();
if (Row!=rowToCompare)
{
ExitValue = false;
break;
}
if (DuplicatedRow)
{
C1TrueDBGrid.Splits[0].DisplayColumns[tgdGroupsUsers.Col].DataColumn.Value = DBNull.Value;
MessageBox.Show("Sorry: but this item(s) is already Exists ", "Error Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
ExitValue = true;
e.Cancel = true;
}
}
}
}
else
{
//Clear Fields
C1TrueDBGrid.Splits[0].DisplayColumns[C1TrueDBGrid.Col].DataColumn.Value = null;
e.Cancel = true;
}
}
if not duplicated below is the code which I am using in (AfterColUpdate)Event:
private void C1TrueDBGrid_AfterColUpdate(object sender, C1.Win.C1TrueDBGrid.ColEventArgs e)
{
if (!ExitValue)
{
int indexRow = this.C1TrueDBGrid.RowBookmark(this.C1TrueDBGrid.Row);
this.C1TrueDBGrid[indexRow, 0] = CSystemUsers.GroupsCode;
this.C1TrueDBGrid[indexRow, 0] = CSystemUsers.EngName;
}
}
componentone answer me the question:
private void c1TrueDBGrid1_BeforeColUpdate(object sender, C1.Win.C1TrueDBGrid.BeforeColUpdateEventArgs e)
{
if (e.ColIndex == 1)
{
for (int i = 0; i < c1TrueDBGrid1.RowCount; i++)
{
if (c1TrueDBGrid1.Editor.Text == c1TrueDBGrid1[i, e.ColIndex].ToString())
{
MessageBox.Show("Sorry: but this item(s) already Exists", "Error Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Cancel = true;
}
}
}
}
link:
http://our.componentone.com/groups/topic/how-do-i-prevent-duplicate-entries-in-c1truedbgrid/
hope this helps someone else in future:

How to check if "Count equals 50 then"?

Edited question totally for more understanding.
I have a count function, and I have a label who checks the current count
Here is the label
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
}
How do I make so once the label reaches as example 50, a function starts. like play sound?
//////////////////////////////
Here is the current one that #btc sources, gave me
private void currentCountLabel_Click(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"sound.wav");
player.Play();
}
}
But it wont play automaticly, how do I make it to play when it reaches the number?
///////////////////////////////////////////////////////////////////////////////
private void currentCountLabel_TextChanged(object sender, EventArgs e)
{
if (String.Compare(currentCountLabel.Text, "5") == 0)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"meme.wav");
player.Play();
}
}
private void writeToFile()
{
if (Properties.Settings.Default.OBSToggle)
{
if (Properties.Settings.Default.ReverseOrder)
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Count.ToString(), Message));
}
else
{
File.WriteAllText(#"Count.txt", String.Format("{0} {1}", Message, Count.ToString()));
}
}
private void KeyBoardHook_KeyUp(object sender, KeyEventArgs e)
{
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyIn)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count + 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count + 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
if (Properties.Settings.Default.HotKeyEnabled && e.KeyCode == Properties.Settings.Default.HotKeyDe && Count != 0)
{
if (Properties.Settings.Default.SaveCount)
{
Count = Count - 1;
Properties.Settings.Default.Count = Count;
currentCountLabel.Text = Properties.Settings.Default.Count.ToString();
}
else
{
Count = Count - 1;
currentCountLabel.Text = Count.ToString();
}
Message = messageTextBox.Text;
writeToFile();
e.Handled = true;
}
}
You need a static variable to hold the current count. Initialized to zero. Then increment it each time the function executes.
Then an if statement to evaluate the count and take whatever action.

How to count the number of "correct" and "incorrect" responses

I'm new to coding and am creating a windows form application in C#. I was having difficulties figuring out how to track the number of correct and incorrect responses. When a button is clicked, if the response is correct a label says correct. I want a different label to count the amount of times it says correct and incorrect. Here's what I was thinking but didn't work.
int add = 0;
add = int.Parse(correct.Text);
if (label1.Text == "Correct")
{
correct.Text = add++;
}
else
incorrect.text = add++;
correct and incorrect are names of my label.
Here's my button click event, there are many alike.
private void G_Click(object sender, EventArgs e)
{
if (go.Visible == true)
{
go.Visible = false;
Random rnd = new Random();
int y = rnd.Next(1, 7);
if (y == 1)
{
eo.Visible = true;
}
if (y == 2)
{
ao.Visible = true;
}
if (y == 4)
{
dd.Visible = true;
}
if (y == 5)
{
go.Visible = true;
}
if (y == 6)
{
eeo.Visible = true;
}
timer1.Start();
label1.Text = "Correct";
}
else
{
label1.Text = "Incorrect";
}
private int correctCount = 0;
private int incorrectCount = 0;
if (label1.Text = "Correct";)
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
The immediate problem is that the type of the Text property is string, not int - you have to set it to text, not a number. Fortunately, you can just call ToString on an int to get a string representation. However, I'd suggest there are other things to change too.
I would strongly suggest that you keep separate counters as variables. While you could keep parsing your labels, it's simpler for them to be purely output. So you might have:
// Fields
private int correctCount = 0;
private int incorrectCount = 0;
...
// Wherever your code is
if (correctAnswer)
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
Note the correctAnswer condition here - we don't know what's setting the text of label1, but I'd suggest that that's the right place to also change the correct/incorrect counters, from the same condition. Again, treat label1 just as output, rather than as a feedback system.
class fields = variables that are declared outside of a method and directly inside a class
local variables = variables that are declared inside of a method
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 deleteMe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int correctCount = 0; // field
private int incorrectCount = 0; // field
private void G_Click(object sender, EventArgs e)
{
if (go.Visible == true)
{
go.Visible = false;
Random rnd = new Random();
int y = rnd.Next(1, 7); // local variable
if (y == 1)
{
eo.Visible = true;
}
if (y == 2)
{
ao.Visible = true;
}
if (y == 4)
{
dd.Visible = true;
}
if (y == 5)
{
go.Visible = true;
}
if (y == 6)
{
eeo.Visible = true;
}
timer1.Start();
incorrect.Text = "Correct";
}
else
{
incorrect.Text = "Incorrect";
}
if (label1.Text = "Correct")
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
}
}
}
== equality. (for comparing 2 values)
= assign a value. (for initialize a variable or field)

Categories

Resources