I'm having issue trying to assign different number values to a number a Radiobuttons, to then calculate together as a total sum into a textbox, but not sure where to start, im new to C# and not understanding to well, if anyone can provide a simple example I would be grateful
So far I've come up with something like this, just to try to assing the number value but cant get it to work, and not even sure how to add them together after? Do I need to use: int?
int Basic, Reg, Pre
{
If RadioButton1.Checked = True Then
Basic = 10;
If RadioButton1.Checked = True Then
Reg = 15;
If RadioButton1.Checked = True Then
Pre = 20;
CodePudding user response:
Looks mostly like Visual Basic. Try to find a beginner's tutorial on C# on the internet.
In this case the variables may not be assigned a value in the if statements. Unlike vb, you need to explicitly assign the default values to the variables before we try to add them at the end.
In C# If is if (most statements are lowercase) and the condition (the part that evaluates to true of false) is in parentheses.
In C# the assignment operator = is different from the comparison operator == which is used in many if statements. You could write
if (radioButton1.Checked == true)
but, since .Checked evaluates to true or false you can skip the == true.
if (radioButton2.Checked)
The code
private void button1_Click(object sender, EventArgs e)
{
int Basic = 0;
int Reg = 0;
int Pre = 0;
if (radioButton1.Checked == true)
Basic = 10;
if (radioButton2.Checked)
Reg = 15;
if (radioButton3.Checked)
Pre = 20;
txtTotal.Text = (Basic Reg Pre).ToString();
}
One last thing. ToString requires the method invoker (). vb is lazy about this. vb also allows you to skip it for constructors but you will need it in C#.
EDIT Users can enter anything in a text box. To keep your code from blowing up it is best to use TryParse to verify a valid number. The first parameter is the string you want to convert. The second is a variable of the appropriate type to hold the converted value. The function returns True of False depending on the success of the conversion. The exclamation mark is Not in C#. If the conversion fails we inform the user and exit the method with return. If successful we continue to the multiplication with the converted values.
private void Button2_Click(object sender, EventArgs e)
{
if (!Double.TryParse(textbox5.Text,out double txt1))
{
MessageBox.Show("Please enter a valid number in textbox 5");
return;
}
if (!Double.TryParse(textbox6.Text,out double txt2))
{
MessageBox.Show("Please enter a valid number in textbox 6");
return;
}
double sum = txt1 * txt2;
textbox7.Text = sum.ToString();
}
