Thrown system.exception.stackoverflowexception C# - c#

In my C# windows form application, there is a combo box that has 3 options in it, when selecting second one a switch command that checks options of another combo box throws and exception of type stack overflow, with this details:
System.StackOverflowException occurred
HResult=0x800703E9
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
Update:
this is the event of index change in combo box:
private void cmbxDoorType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbxDoorType.SelectedIndex == 0)
{
chkTopBlock.Enabled = true;
if(chkTopBlock.Checked)
cmbxTopBlockConfig.Enabled = true;
cmbxTopSideConfig.Enabled = true;
txtDoorHeight.ReadOnly = false;
txtTotalWidth.Visible = false;
lblTotalWidth.Visible = false;
lblDoorBaleWidth.Enabled = false;
}
else if (cmbxDoorType.SelectedIndex == 1)
{
txtTotalWidth.Visible = false;
lblTotalWidth.Visible = false;
lblDoorBaleWidth.Enabled = false;
cmbxTopBlockConfig.Enabled = false;
chkTopBlock.Enabled = false;
txtDoorHeight.ReadOnly = true;
cmbxTopSideConfig.Enabled = false;
}
else
{
chkTopBlock.Enabled = true;
if (chkTopBlock.Checked)
cmbxTopBlockConfig.Enabled = true;
cmbxTopSideConfig.Enabled = true;
txtDoorHeight.ReadOnly = false;
txtTotalWidth.Visible = true;
lblTotalWidth.Visible = true;
lblDoorBaleWidth.Enabled = true;
}
Prediction();
}
this is the prediction methode than exception ocours in:
internal void Prediction ()
{
if (Globals.ProjectType=="Gama")
{
int TotalHeight_=0;
double DesignHeight_=0;
int TotalWidth_=0;
double LeftDis = 0;
double RightDis = 0;
double RowsTotalHeight_=0;
double TopBlockHeight_=0;
double thisDoorHeight_ = 0;
int DoorHeight_=0;
int DoorWidth_=0;
double DoorBaleWidth_=0;
try
{
switch (cmbxLeftSideConfig.SelectedIndex) //exception thrown here
{
case 0:
LeftDis = GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 2:
LeftDis = GamaGlobals.Constants.GP115Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 3:
LeftDis = GamaGlobals.Constants.GP114Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 4:
LeftDis = GamaGlobals.Constants.GP117Height - GamaGlobals.Constants.InsertOffset;
break;
case 1:
LeftDis = 0;
break;
}
switch (cmbxRightSideConfig.SelectedIndex)
{
case 0:
RightDis = GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 2:
RightDis = GamaGlobals.Constants.GP115Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 3:
RightDis = GamaGlobals.Constants.GP114Body + GamaGlobals.Constants.BeamThickness - GamaGlobals.Constants.InsertOffset;
break;
case 4:
RightDis = GamaGlobals.Constants.GP117Height - GamaGlobals.Constants.InsertOffset;
break;
case 1:
RightDis = 0;
break;
}
}

Something in your cmbxDoorType_SelectedIndexChanged, or another SelectedIndexChanged event will retrigger your event again, which makes it a StackOverFlowException after a couple of seconds

in "prediction" method there was a line that changes a textbox value, and that text box itself has a value changed event that triggers "prediction" again.
so it's solved.
just as another question, is there a way to change textbox/numericupdown controls value programmatically without triggering its change event?
for example, if the user changes it, it triggers event but when its programmatically changed, the event does not trigger.
hm??

Related

Switch case goes to default except one case

when i tried to use the Switch case function, it goes always to the default message besides case 5:
private void btnCandlesLight_Click(object sender, EventArgs e)
{
int result;
result = Convert.ToInt32(textBox1.Text);
switch(result)
{
case 1:
day1.Start();
candlesOne();
break;
case 2:
day2.Start();
candlesTwo();
break;
case 3:
day3.Start();
candlesThree();
break;
case 4:
day4.Start();
candlesFour();
break;
case 5:
day5.Start();
candlesFive();
break;
case 6:
day6.Start();
candlesSix();
break;
case 7:
day7.Start();
candlesSeven();
break;
case 8:
day8.Start();
candlesEight();
break;
default:
MessageBox.Show("Enter new day");
break;
}
}
When I Enter the value 1 for example to the text box, the default case works, but only when I enter the value 5 it works perfectly.
If you want to see the difference between the function "candlesOne" to "candlesFive":
The "c" variable is a variable of the seconds. i tried to use a timer in a way of lighting up the candles every 2-3 seconds.
public void candlesOne()
{
firedmatch.Left = firedmatch.Left + 100;
if (c == 1)
{
candle1.Visible = true;
}
if (c == 3)
{
candle2.Visible = true;
}
}
and:
public void candlesFive()
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3)
{
candle2.Visible = true;
}
if(c == 5)
{
candle3.Visible = true;
}
if(c == 7)
{
candle4.Visible = true;
}
if(c == 11)
{
candle5.Visible = true;
}
}
I haven't found a mistake,
can you guys help me?
Thanks
Have you checked if you really get for example (int)1 as a result of the "1" input from your conversion?
On a broader scale, there is a lot of repetition in your code, you should consider refactoring it a little.
In your CandlesOne and CandlesFive methods, you use a c variable, no idea what that is or where it comes from. Those two methods (and probably the other CandlesXXX() do the same kind of things. Can't you remove complexity by generalizing the logic? Can the result used in your switch-case be passed as a parameter and used to trigger the numbers of c == X calls in the CandleXXX() methods?
This way you could remove the switch and lose a lot of complexity!
Edit
If you have further problems, consider creating a .NET Fiddle, I miss a lot of context in your code so I cannot efficiently help you here.
Some refactoring ideas for you:
// Somewhere else in your code, create a dictionary with your day1-day8 objects
var days = new Dictionary<int, Day>()
days[1] = day1;
...
days[8] = day8;
//Simplfiy your method
private void btnCandlesLight_Click(object sender, EventArgs e)
{
try
{
var dayIndex = Convert.ToInt32(textBox1.Text);
if(dayIndex > 0 && dayIndex <= 8)
{
days[dayIndex].Start(); //Get the corresponding day via its Key
LightUpCandles(dayIndex); //pass the key as a parameter
}
else
{
MessageBox.Show("Enter new day");
}
}
catch(InvalidCastException exception)
{
//Whatever you do when the textbox cannot be parsed
}
}
I still don't get what your candlesOne to five methods are really doing or why the method "candlesOne" lights up two candles (pay attention to the variable naming). I also don't get how this makes up some kind of timer... but here's a first potential refactoring for it anyway:
public void LightUpCandles(int dayIndex)
{
firedmatch.Left = firedmatch.Left + 100;
if(c == 1)
{
candle1.Visible = true;
}
if(c == 3 && dayIndex > 1)
{
candle2.Visible = true;
}
if(c == 5 && dayIndex > 2)
{
candle3.Visible = true;
}
if(c == 7 && dayIndex > 3)
{
candle4.Visible = true;
}
if(c == 11 && dayIndex > 4)
{
candle5.Visible = true;
}
}
Your switch logic is correct which I tested with the following;
int result;
result = Convert.ToInt32(textBox1.Text);
switch (result)
{
case 1:
MessageBox.Show("1");
break;
case 2:
MessageBox.Show("2");
break;
case 3:
MessageBox.Show("3");
break;
case 4:
MessageBox.Show("4");
break;
case 5:
MessageBox.Show("5");
break;
case 6:
MessageBox.Show("6");
break;
case 7:
MessageBox.Show("7");
break;
case 8:
MessageBox.Show("8");
break;
default:
MessageBox.Show("Enter new day");
break;
}
If you don't get the same results I would perhaps look at making the message boxes above display the data type of the variable.
MessageBox.Show(result.GetType().ToString());

C# Repeater gives exception on NEXT Button Click : 'ddlPageNo' has a SelectedIndex which is invalid

I am using repeater to load data, it shows following exception on Next button click in following scenario
I have to dropdown
1. it shows number of pages (ddlPageNo)
2. it shows how many rows I want to show(ddlPageSize)
so when I have 9 values and if I keep value of 2nd dropdown(ddlPageSize) 10
and click the next button then it gives exception
'ddlPageNo' has a SelectedIndex which is invalid because it does not exist in the list of items. Parameter name: value
there is my code :
void fillRepeater(PageNavigation pageNavigate, string strMode)
{
IUser objUser = (clsUser)FactoryUser.getUser();
DataTable dtUsers = null;
DataView dvUsers = new DataView();
PagedDataSource pdsUsers = new PagedDataSource();
try
{
dvUsers = getUsers(strMode);
pdsUsers.DataSource = dvUsers;
pdsUsers.AllowPaging = true;
dvUsers.Sort = "UserName asc";
pdsUsers.PageSize = Int16.Parse(ddlPageSize.SelectedValue);
int iPageCount = pdsUsers.PageCount;
if (ddlPageNo.Items.Count != iPageCount)
{
ddlPageNo.Items.Clear();
for (int kk = 1; kk <= iPageCount; kk++)
{
ListItem lstPage = new ListItem(kk.ToString(), kk.ToString());
ddlPageNo.Items.Add(lstPage);
}
ddlPageNo.SelectedIndex = 0;
}
switch (pageNavigate)
{
case PageNavigation.Next:
UserViewCurrentPage++;
ddlPageNo.SelectedIndex = UserViewCurrentPage;
break;
case PageNavigation.Previous:
UserViewCurrentPage--;
ddlPageNo.SelectedIndex = UserViewCurrentPage;
break;
case PageNavigation.Last:
UserViewCurrentPage = pdsUsers.PageCount - 1;
ddlPageNo.SelectedIndex = UserViewCurrentPage;
break;
case PageNavigation.Sorting:
break;
case PageNavigation.GotoPage:
UserViewCurrentPage = int.Parse(ddlUserPageNo.SelectedValue) - 1;
break;
case PageNavigation.Current:
break;
case PageNavigation.Size:
UserViewCurrentPage = 0;
ddlPageNo.Items.Clear();
if (ddlPageNo.Items.Count == 0)
{
for (int kk = 1; kk <= iPageCount; kk++)
{
ListItem lstPage = new ListItem(kk.ToString(), kk.ToString());
ddlPageNo.Items.Add(lstPage);
}
ddlPageNo.SelectedIndex = 0;
}
break;
default: UserViewCurrentPage = 0; ddlPageNo.SelectedIndex = 0;
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
Suppose page size is 5 and number of pages are 2 , if there are 9 values in table so when we click on next button for 1st time 4 values remain on page. so ideally next button must be disabled (which I have achieved with CSS but still that button is clickable ) but it allows to click and on click above exception throws

Cannot calculate decimals in my calculator

So, I have made a calculator in C# but it cannot calculate decimal numbers.
It works perfectly fine when clicking on for example the buttons: 6 then . (this is a dot) then 5. But as soon as I click on the "+"-button (or any other operator) afterwards in the form, the program stops and I get a message saying that
"An unhandled exception of type 'System.FormatException' occured in
mscorlib.dll. The input string was not in a correct format".
I don't know exactly how to solve this. Is there anyone that knows how to solve this problem?
Here is my code:
namespace Kalkylator{
public partial class Form1 : Form{
String operation = ""; //the operation we will use
Double resultat = 0; //the result we will get
bool finished = false; //if false, we have not pressed the "=" button yet
public Form1(){
InitializeComponent();
}
//
private void button_click(object sender, EventArgs e){
if (finished == true){ //if we press any operator, clear the textbox-window so new numbers can be entered
textBoxFonster.Clear();
}
finished = false; //we are not done with the calculation
Button b = (Button)sender;
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
else{
textBoxFonster.Text = textBoxFonster.Text + b.Text; //writes the number in the textBox
}
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text; //the operation we will perform is the operatorButton we will press
resultat = Double.Parse(textBoxFonster.Text); //HERE IS WHERE THE PROGRAM GIVES ME THE ERROR.
finished = true; //we are done with the calculation
}
private void clear_click(object sender, EventArgs e)
{
textBoxFonster.Text = ""; //clear the window from all text
resultat = 0; //clear the value of resultat and set it to 0
}
private void LikaMed_click(object sender, EventArgs e)
{
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
case "*":
textBoxFonster.Text = (resultat * Double.Parse(textBoxFonster.Text)).ToString();
break;
case "%":
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text) * (resultat/100)).ToString();
break;
case "^":
textBoxFonster.Text = (Math.Pow(resultat, Double.Parse(textBoxFonster.Text))).ToString();
break;
case "Log": //takes the 10th log of resultat
textBoxFonster.Text = (Math.Log10(resultat)).ToString();
break;
case "Sqrt":
textBoxFonster.Text = (Math.Sqrt(resultat)).ToString();
break;
case "/": //divide the result with the text in the textBox if that text is not 0. If so, show an error message
if ((Double.Parse(textBoxFonster.Text)) != 0){
textBoxFonster.Text = (resultat / Double.Parse(textBoxFonster.Text)).ToString();
}
else{ //show error in MessageBox
MessageBox.Show("Cannot divide by 0!");
}
break;
default:
break;
}
finished = true; //this will clear the result textbox when clicking another number after the equal sign has been clicked
}
}
}
Don't use Double.Parse without specifying the Culture.
Change:
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (resultat + Double.Parse(textBoxFonster.Text)).ToString();
break;
case "-":
textBoxFonster.Text = (resultat - Double.Parse(textBoxFonster.Text)).ToString();
break;
to:
Double operand1=resultat;
Double operand2=0;
Double.TryParse(textBoxFonster.Text,NumberStyles.Float,CultureInfo.InvariantCulture,out operand2);
switch(operation){
case "+": //add the result with the text in the textBox
textBoxFonster.Text = (operand1 + operand2).ToString();
break;
case "-":
textBoxFonster.Text = (operand1 - operand2).ToString();
break;
Alternatively, you could actually support multiple cultures, and change this code:
if (b.Text == "."){
if (!textBoxFonster.Text.Contains(".")){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}
to this:
if (b.Text == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator){
if (!textBoxFonster.Text.Contains(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)){
textBoxFonster.Text = textBoxFonster.Text + b.Text;
}
}

Listbox unassigned variable

Full disclosure here, I am a student doing homework. I have 2 listboxes with items that can be selected. What is said in them is not needed to be extracted. I wrote the code out and everything works except I get an error saying "use of unassigned variable" on 3 variables at the end of the code. They are locFees, days, and registration. Can anyone tell me what I am doing wrong that is causing the variables to not have a value?
private void btnCalc_Click(object sender, EventArgs e)
{
double registration, lodging, total, days, locFees;
int workshopIndex, locationIndex;
if (lbWorkshop.SelectedIndex != -1)
{
workshopIndex = lbWorkshop.SelectedIndex;
switch (workshopIndex)
{
case 0:
days = 3;
registration = 1000;
break;
case 1:
days = 3;
registration = 800;
break;
case 2:
days = 3;
registration = 1500;
break;
case 3:
days = 5;
registration = 1300;
break;
case 4:
days = 1;
registration = 500;
break;
}
}
else
{
MessageBox.Show("You didn't select a workshop.");
}
if (lbLocation.SelectedIndex != -1)
{
locationIndex = lbLocation.SelectedIndex;
switch (locationIndex)
{
case 0:
locFees = 150;
break;
case 1:
locFees = 225;
break;
case 2:
locFees = 175;
break;
case 3:
locFees = 300;
break;
case 4:
locFees = 175;
break;
case 5:
locFees = 150;
break;
}
}
else
{
MessageBox.Show("You didn't select a city.");
}
lodging = locFees * days;
total = registration + lodging;
}
Can anyone tell me what I am doing wrong that is causing the variables to not have a value?
Sure - you're ignoring the possibility that workshopIndex isn't 0, 1, 2, 3 or 4.
If you believe that should never happen, just add:
default:
throw new InvalidOperationException("Invalid selected index " + workshopIndex);
Or if you just want to use some defaults, do something like:
default:
days = 1;
registration = 100;
break;
That's the first way you can end up with days and registration unassigned.
Next, there's the fact that you only go into the switch block at all if lbWorkshop.SelectedIndex != -1. Your else block is just:
else
{
MessageBox.Show("You didn't select a workshop.");
}
... so after that else block, you're going to continue. You probably want:
else
{
MessageBox.Show("You didn't select a workshop.");
return;
}
You've then got the same problem for locFees, in terms of both the switch statement and the else block.
One thing to learn from this: be grateful that the compiler spotted these for you. It's stopped you from running code which definitely had bugs in. That's always a good thing.

image not displaying

I hope you can help me! I am trying to make a game similiar to candyland. I want the die to spin when the user clicks the button. A random number is chosen and based on that number, the dice displays the image for that number. That works! Then, I want our user to be able to move forward on our board- based on the spot that they're on, it adds whatever they spinned and the image on that spot becomes visible. When in debug mode, everything works perfectly but for some reason, the pawn never moves! Can you please tell me why. I am attaching my code below. Thank you so much!
protected void btnSpin_Click(object sender, EventArgs e)
{
Random randomNumber = new Random();
int x = randomNumber.Next(1, 6);
switch (x)
{
case 1:
//imgDie.ImageUrl = "~/Images/dice1.jpg";
Session["Die"] = "~/Images/dice1.jpg";
break;
case 2:
Session["Die"] = "~/Images/dice2.jpg";
break;
case 3:
Session["Die"] = "~/Images/dice3.jpg";
break;
case 4:
Session["Die"] = "~/Images/dice4.jpg";
break;
case 5:
Session["Die"] = "~/Images/dice5.jpg";
break;
case 6:
Session["Die"] = "~/Images/dice6.jpg";
break;
}
imgDie.ImageUrl = (string)Session["Die"];
place = place + x;
switch (place)
{
case 2:
img2.Visible = true;
img2.ImageUrl = (string)Session["Imagesrc"];
break;
case 3:
img3.Visible = true;
img3.ImageUrl = (string)Session["Imagesrc"];
break;
case 4:
img4.Visible = true;
img4.ImageUrl = (string)Session["Imagesrc"];
break;
case 5:
img5.Visible = true;
img5.ImageUrl = (string)Session["Imagesrc"];
break;
case 6:
img6.Visible = true;
img6.ImageUrl = (string)Session["Imagesrc"];
break;
case 7:
img7.Visible = true;
img7.ImageUrl = (string)Session["Imagesrc"];
break;
case 8:
img8.ImageUrl = (string)Session["Imagesrc"];
img8.Visible = true;
break;
my guess is your 'place' variable is a member field and it's being reinitialized with each page construction. chnge your place variable to be viewstate or session state like your other stuff.

Categories