If I have code that is executed by a button statement and I would like this code to be executed at different times from other actions can I use a goto stateent to execute it? If so how. I can't seem to find a correct way or method to label the code that is executed so the goto statement is correct.

My code looks like this. How would I name my goto statement to get here. Thanks in advance.

private void calculateBN_Click(object sender, EventArgs e)
{
"calculations"
}

Recommended Answers

All 6 Replies

Put the code you want in a function and call the function. You can't use goto statements across functions -- that wouldn't even make any sense.

Its a bad habbit to use gotos without purpose (which that would be)

simple answer

Make a method

when you need it, call the method, wether its from that action or from your other code.

Im new at programming. How do you call the method.

Wow, did you really just ask that?
So you in your code you only now how to add things up and set values?

This illustrates having each method (also called a procedure or function in other languages) having a single task that way you can call the code from anywhere (eliminating the need for a goto). If this doesn't address how you can solve your problem then you need to post the code you currently have and outline your problem.

Goto is a hack for allowing bad design and is not a best practice in use or concept.

buttonSave_click(object sender, eventargs e)
{
  CalculateTotals();
  SaveInvoice();
  this.Close();
}

buttonRecalculate_Click(object sender, eventargs e)
{
  CalculateTotals();
}

private void CalculateTotals()
{
  decimal serviceAmt = decimal.Parse(textEditService.Text);
  decimal productAmt = decimal.Parse(textEditProducts.Text);
  textEditTotalAmt.Text = Convert.ToString(serviceAmt+productAmt);
}

private void SaveInvoice()
{
  dsInvoice[0]["ServiceAmt"] = decimal.Parse(textEditService.Text);
  dsInvoice[0]["ProductAmt"] = decimal.Parse(textEditProducts.Text);
  dsInvoice[0]["Total"] = decimal.Parse(textEditService.Text)+ decimal.Parse(textEditProducts.Text);
}

Im new at programming. How do you call the method.

You really just need to learn how to program. Follow whatever book or high quality tutorial you're using and burn through the basics.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.