Hi have have an if statement inside the event of a button, when i run the code and select the first radio and click on the button(which does the calculations) it prints it out on the label, but when i click on the second radio button and click the button to calculate the answer nothing happens at all. Any ideas please
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
}�
The problem is that you are checking for the condition of radiobutton1 being checked first and then nested other conditions inside it, so if the first condition is false the other conditions are not being checked, so to avoid that you should bring the other else if-conditions outside the first if-condition, you can use:-
private void button1_Click(object sender, EventArgs e)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (radioButton1.Checked == true)
{
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
if (success)
{
label3.Text = ConvertToFar(a).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
That's because radio buttons are mutually exclusive, and you are only executing the code if radioButton1 is checked. You should probably also handle the case where the textbox could not be parsed correctly (i.e. if the user enters something that cannot be converted to a double). I've included this below.
double a;
bool success = double.TryParse(textBox1.Text, out a);
if (success)
{
if (radioButton1.Checked == true)
{
label4.Text = ConvertToCel(a).ToString();
}
else if (radioButton2.Checked == true)
{
label3.Text = ConvertToFar(a).ToString();
}
else
{
label4.Text = "Please select an option from above";
}
}
else
{
label4.Text = "The value could not be convered to a number.";
}
That's because you have put the else on the if statement inside the first if statement. The checks for radiobutton 2 will only be run if the condition in the first if statement is true.
End the block for the first if statement before the else statements:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
double a; // have to declare double here as we cannot include it below as bool is a rue or false statment
bool success1 = double.TryParse(textBox1.Text, out a); // take in value as true or false
if (success1) // check if it was parsed successful
{
label4.Text = ConvertToCel(a).ToString(); // now set it in label
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == true)
{
double a1;
bool success = double.TryParse(textBox1.Text, out a1);
if (success){
label3.Text = ConvertToFar(a1).ToString();
}
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
{
label4.Text = "Please select an option from above";
}
}
Related
I tried to get value of checked checkbox in DataGridView, so I check if value is true or false:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
{
dataGridView1.Rows[i].Cells["check"].Value = false;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = true;
}
button2.Enabled = (counter > 0);
}
}
}
}
It involks an error in line:
if ((bool)dataGridView1.Rows[i].Cells["check"].Value == true)
Second solution:
if (dataGridView1.Rows[i].Cells["check"].Value == null || (bool)dataGridView1.Rows[i].Cells["check"].Value == false)
{
dataGridView1.Rows[i].Cells["check"].Value = true;
counter++;
}
else
{
dataGridView1.Rows[i].Cells["check"].Value = false;
counter--;
}
The code below works, but sometimes checkbox is not checked
I am doing something really similar in a project of mine,
I am only using OnCellValueChanged instead of CellContentClick.
Here's my working line of code
bool completed = Convert.ToBoolean(dgv.Rows[e.RowIndex].Cells[1].Value.ToString());
What is exactly your error? Did you try to see what .Value was in the debugger ?
I'm new here and I have a problem (I think the solution is simple, but I can't solve this problem alone). I have to throw a few checkbox on userform (that is simple) but when I write something like this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("co nie tak");
}
always get "ok1" MsgBox...
Any ideas what I'm doing wrong? Thanks for helping.
The if statement will always go into the first block that is true. So if checkbox1 is checked you will always get "ok1". You can never get into the second block ( "ok2" ) because if it is true, the first check would also be true.
I think you want to switch your checks:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
You may also be looking to build up your string by adding to it. The += means add to the end of the string.
My example code is just an example, since I don't really know what you are trying to do, but it might give you some ideas.
if (checkBox1.checked )
{
mic.HTMLBody = "1) Example1";
}
if ( checkBox2.checked )
{
mic.HTMLBody += "<br>"""2) Example2";
if ( ComboBox2.Text == "Pan" )
{
mic.HTMLBody += "<br>Pana";
}
}
from the code i see if checkbox1.checked is true then "ok1" should display and the second an third evaluations would never be evavluated. if checkbox1.checked is false then only the third option would be evaluated and the second option should never be evaluated at all. Should be more like:
if (checkBox1.Checked)
{
if (checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else
{
MessageBox.Show("ok1");
}
}
else
{
MessageBox.Show("co nie tak");
}
As it is currently written, it is impossible for it to enter the else if, because whenever the else if condition is true, the if condition is also true.
It goes from up to down, the first that is true is entered and the rest are ignored.
Instead you should switch their place as follows:
if(checkBox1.Checked && checkBox2.Checked)
{
MessageBox.Show("ok2");
}
else if(checkBox1.Checked)
{
MessageBox.Show("ok1");
}
else
{
MessageBox.Show("co nie tak");
}
A little unclear what you really want shown, but if you want it to first show ok1 and then ok2 then you can do this:
if(checkBox1.Checked)
{
MessageBox.Show("ok1");
if(checkBox2.Checked) {
MessageBox.Show("ok2");
//MessageBox.Show("ok1 ok2"); //If you want to show them both at the same time
}
}
else
{
MessageBox.Show("co nie tak");
}
I tried this one on a Console and it might be the logic you need. The inline comments will give you a bit of insight of what is doing what:
check1 = true;
check2 = true;
if (check1)
{
if (check2)
{
// Prints if BOTH check1 and check2 are TRUE
Console.WriteLine("ok2");
}
else
{
// Prints if ONLY check1 is TRUE
Console.WriteLine("ok1");
}
}
else
{
// Prints if BOTH check1 and check2 are FALSE
Console.WriteLine("co nie tak");
}
bool Check = checkBox1.Checked;
bool Check2 = checkBox2.Checked;
if (Check == true && Check2 == true)
{ MessageBox.Show("ok 1 & 2"); }
if (Check == true)
{ MessageBox.Show("ok 1"); }
if (Check2 == true)
{ MessageBox.Show("ok 2 "); }
else
{ MessageBox.Show("Not Checked"); }
This question already has answers here:
Only one checkbox to be selected
(6 answers)
Closed 6 years ago.
I am struggling with why my code is not working. This is for a school assignment. I am allowed to ask for help. I am new to programming. I am using visual studio 2015. I am trying to get it so the user must only be allowed to select one checkbox. I have other checkboxes in this assignment so using last checked will not work. I am not getting errors, it just does nothing. Thanks!
My checkBoxes are named checkBox1, checkBox2,......5
My entire current code is:
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 Chapter6Homework
{
public partial class IceCreamOrder : Form
{
public IceCreamOrder()
{
InitializeComponent();
}
private void btn_Clear_Click(object sender, EventArgs e)
{
// Clear flavors by automatically selecting default button on Clear button click
rdbDefault.Checked = true;
// Clear toppings
checkBox_CookieDough.CheckState = CheckState.Unchecked;
checkBox_ChocolateSyrup.CheckState = CheckState.Unchecked;
checkBox_Marshmallows.CheckState = CheckState.Unchecked;
checkBox_OreoPieces.CheckState = CheckState.Unchecked;
checkbox_Sprinkles.CheckState = CheckState.Unchecked;
checkbox_Walnuts.CheckState = CheckState.Unchecked;
// Clear List Box
lstDisplay.Items.Clear();
// Clear scoops
checkBox1.CheckState = CheckState.Unchecked;
checkBox2.CheckState = CheckState.Unchecked;
checkBox3.CheckState = CheckState.Unchecked;
checkBox4.CheckState = CheckState.Unchecked;
checkBox5.CheckState = CheckState.Unchecked;
}
private void btn_CalculateCost_Click(object sender, EventArgs e)
{
// Verify user selected a flavor
if (rdbDefault.Checked == true)
{
MessageBox.Show("Please select a flavor");
return;
}
// Verify user seleted # of scoops
if (checkBox1.CheckState == CheckState.Unchecked &&
checkBox2.CheckState == CheckState.Unchecked &&
checkBox3.CheckState == CheckState.Unchecked &&
checkBox4.CheckState == CheckState.Unchecked &&
checkBox5.CheckState == CheckState.Unchecked)
{
MessageBox.Show("You must select a number of scoops. 1 is a must but 5 is recommended!");
return;
}
//Verify user got the toppings they wanted if any
if (checkBox_ChocolateSyrup.CheckState == CheckState.Unchecked &&
checkBox_CookieDough.CheckState == CheckState.Unchecked &&
checkBox_Marshmallows.CheckState == CheckState.Unchecked &&
checkBox_OreoPieces.CheckState == CheckState.Unchecked &&
checkbox_Sprinkles.CheckState == CheckState.Unchecked &&
checkbox_Walnuts.CheckState == CheckState.Unchecked)
{
DialogResult dr = MessageBox.Show("Are you sure you don't want toppings?",
"help", MessageBoxButtons.YesNo);
switch (dr)
{
case DialogResult.Yes: break;
case DialogResult.No: return;
}
}
// Declare Variables and constants
double flavorCost = FlavorCost();
double toppingCost = ToppingCost();
double scoops = Scoops() * flavorCost;
double subTotal = (flavorCost + toppingCost + scoops);
double salesTax = subTotal * .08;
double total = subTotal + salesTax;
// Display total price of order
lstDisplay.Items.Clear();
lstDisplay.Items.Add("Total: " + total.ToString("C2"));
// Display total sales tax
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Sales Tax: " + salesTax.ToString("C2"));
// Display Flavor Cost
lstDisplay.Items.Add("Flavor: " + flavorCost.ToString("C2"));
// Display Scoops Cost
lstDisplay.Items.Add("Scoops: " + scoops.ToString("C2"));
// Display Toppings
lstDisplay.Items.Add("Toppings: " + toppingCost.ToString("C2"));
}
// Get flavor cost
Double FlavorCost()
{
if ((radioButton_Chocolate.Checked == true) || (radioButton_Strawberry.Checked == true))
return 1.5F;
else if (radioButton_Vanilla.Checked == true)
return 1.25F;
else
return 0;
}
// Get num of scoops
Double Scoops()
{
if (checkBox1.Checked == true)
return 1;
else if (checkBox2.Checked == true)
return 2;
else if (checkBox3.Checked == true)
return 3;
else if (checkBox4.Checked == true)
return 4;
else if (checkBox5.Checked == true)
return 5;
else
return 0;
}
// Get Toppings
Double ToppingCost()
{
if ((checkBox_ChocolateSyrup.Checked == true) ||
(checkBox_Marshmallows.Checked == true) ||
(checkbox_Sprinkles.Checked == true))
return .25F;
else if ((checkBox_OreoPieces.Checked == true) ||
(checkBox_CookieDough.Checked == true) ||
(checkbox_Walnuts.Checked == true))
return .50F;
else
return 0;
}
private void IceCreamOrder_Load_1(object sender, EventArgs e)
{
//Set Default to true on load
rdbDefault.Checked = true;
}
internal class Sub
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
int numberChecked = 0;
CheckBox[] array = new
CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
for (int i = 0; i < array.Length; i++)
{
if
(array[i].Checked)
numberChecked++;
else if
(numberChecked > 1)
MessageBox.Show("You have checked "
+ numberChecked.ToString() + " checkBoxes. Only one is allowed.");
else
return;
}
}
}
}
Use RadioButton with grouping.
To make your solution work: ( sender is the selected checkbox )
private void checkBox1_Checked(object sender, EventArgs e)
{
var array = new CheckBox[] { checkBox1, checkBox2, checkBox3, checkBox4, checkBox5 };
foreach(var checkbox in array)
{
if(checkbox != sender){
checkbox.IsChecked = false
}
}
I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}
You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}
Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.
How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precison. I have tried the answers in this question How to make a textBox accept only Numbers and just one decimal point in Windows 8. But it did not work. How can I do this ?
You can write a function like this,
txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);
//Method to allow only numbers,
void EnsureNumbers(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
return;
}
bool result = EnsureDecimalPlaces();
if (result == false)
{
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
else
{
e.Handled = true;
}
}
Method to ensure only 1 decimal,
bool EnsureDecimalPlaces()
{
string inText = txtDiscount.Text;
int decPointIndex = inText.IndexOf('.');
if (decPointIndex < 1 || decPointIndex == 1)
{
return false;
}
else
return true;
}