Esentially I'm trying to turn the below code into a loop. Every time I try to iterate through controls I seem to hit some sort of dead end and can't figure out how to update the relevant label or check the relevant textbox.
if (checkBox1.Checked && !string.IsNullOrEmpty(textBox1.Text))
{
if (RemoteFileExists(textBox1.Text) == true)
{
label1.Text = "UP";
}
else
{
label1.Text = "DOWN";
}
}
if (checkBox2.Checked && !string.IsNullOrEmpty(textBox2.Text))
{
if (RemoteFileExists(textBox2.Text) == true)
{
label2.Text = "UP";
}
else
{
label2.Text = "DOWN";
}
}
if (checkBox3.Checked && !string.IsNullOrEmpty(textBox3.Text))
{
if (RemoteFileExists(textBox3.Text) == true)
{
label3.Text = "UP";
}
else
{
label3.Text = "DOWN";
}
}
You can use Form.Controls to iterate all the controls on the page, so for example:
foreach(Control control in Controls) {
if (control is Checkbox) {
...
} else if (control is TextBox) {
...
} else {
...
}
}
However, this will do ALL controls so might not be efficient. You might be able to use the Tag of your controls and LINQ extensions to improve it, for example:
IEnumerable<Checkbox> needed_checkboxes = Controls.Where(control => control is Checkbox && control.Tag == someValue);
You can use it by finding the controls dynamically:
for (int i = 1; i < count; i++)
{
CheckBox chbx = (CheckBox) this.FindControl("checkBox" + i);
TextBox txtb = (TextBox)this.FindControl("textBox" + i);
Label lbl = (Label) this.FindControl("label" + i);
if (chbx.Checked && !string.IsNullOrEmpty(txtb.Text))
{
if (RemoteFileExists(txtb.Text) == true)
{
lbl.Text = "UP";
}
else
{
lbl.Text = "DOWN";
}
}
}
Related
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
}
}
newbie in learning c# here, im calculating cgpa and when user pick the number of subject they take, accordingly, the textBox will Enabled true according to the number of user subject and the rest is Enabled false. So when im clicking calculateCGPA, i want to popup message if the user input is empty but messageBox is shown x number of time according to the number that user left empty. How to get it to show only once. Tqvm in advanced. Explanation is very much appreciated.
1.CheckingUserCheckedRadioButton
private void DisplayTextBox(Control con)
{
foreach (Control c in con.Controls)
{
if (rad1.Checked)
{
if (c is TextBox)
{
((TextBox)c).Enabled = false;
txtCCode1.Enabled = true;
txtGrade1.Enabled = true;
}
else
{
DisplayTextBox(c);
}
}
}
}
2.DisplayingMessageBoxWhenClickingCalculate
private void calculate(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
if (c.Text == "")
{
DialogResult x = new DialogResult();
x = MessageBox.Show("TextBox cannot be Empty");
if (x == DialogResult.OK)
txtCCode1.Focus();
}
else
{
int totalCredHours = 0;
CalcTotalCredHours(credHour1, credHour2, credHour3, credHour4, credHour5, credHour6, ref totalCredHours);
courseGP1 = CalcCourseGradePoint(credHour1, gradePoint1);
courseGP2 = CalcCourseGradePoint(credHour2, gradePoint2);
courseGP3 = CalcCourseGradePoint(credHour3, gradePoint3);
courseGP4 = CalcCourseGradePoint(credHour4, gradePoint4);
courseGP5 = CalcCourseGradePoint(credHour5, gradePoint5);
courseGP6 = CalcCourseGradePoint(credHour6, gradePoint6);
double totalCGP = CalcTotalCGP(courseGP1, courseGP2, courseGP3, courseGP4, courseGP5, courseGP6);
double gpa = CalcGPA(totalCGP, totalCredHours);
lblGPA.Text = gpa.ToString("N");
}
}
else
{
calculate(c);
}
}
}
Create a method that shows the message box with a global flag:
bool showed = false;
private ShowMessageBox(string message)
{
if (!showed)
MessageBox.Show(message);
showed = true;
}
In you code call this method
ShowMessageBox("TextBox cannot be Empty")
instead of
MessageBox.Shows("TextBox cannot be Empty")
You should have following lines:
static bool showed = false; // <---- This line
private void DisplayTextBox(Control con)
{
if (rad1.Checked)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
((TextBox)c).Enabled = false;
txtCCode1.Enabled = true;
txtGrade1.Enabled = true;
}
else
{
DisplayTextBox(c);
}
}
}
showed = false; // <---- This line
}
private void calculate(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
if (c.Text == "")
{
if (!showed) // <---- This line
{ // <---- This line
showed = true; // <---- This line
DialogResult x = new DialogResult();
x = MessageBox.Show("TextBox cannot be Empty");
if (x == DialogResult.OK)
txtCCode1.Focus();
} // <---- This line
}
else
{
int totalCredHours = 0;
CalcTotalCredHours(credHour1, credHour2, credHour3, credHour4, credHour5, credHour6, ref totalCredHours);
courseGP1 = CalcCourseGradePoint(credHour1, gradePoint1);
courseGP2 = CalcCourseGradePoint(credHour2, gradePoint2);
courseGP3 = CalcCourseGradePoint(credHour3, gradePoint3);
courseGP4 = CalcCourseGradePoint(credHour4, gradePoint4);
courseGP5 = CalcCourseGradePoint(credHour5, gradePoint5);
courseGP6 = CalcCourseGradePoint(credHour6, gradePoint6);
double totalCGP = CalcTotalCGP(courseGP1, courseGP2, courseGP3, courseGP4, courseGP5, courseGP6);
double gpa = CalcGPA(totalCGP, totalCredHours);
lblGPA.Text = gpa.ToString("N");
}
}
else
{
calculate(c);
}
}
}
I you don't want to reshuffle your code much , the best way is to add a break statement if any of the textboxes is Empty.
For e.g
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
if (c.Text == "")
{
DialogResult x = new DialogResult();
x = MessageBox.Show("TextBox cannot be Empty");
if (x == DialogResult.OK)
txtCCode1.Focus();
break;
}
I want to validate all Approve Item on Button click not N/A or Reject.Please suggest me how can I achive this task. Pls see the image.
int sum = 0;
foreach (DataListItem item in dtLstRejection.Items)
{
RadioButtonList rdlReasoncodeType ((RadioButtonList)item.FindControl("rdlReasonType"));
System.Web.UI.WebControls.Label lbldlmsg = (Label)item.FindControl("lbldlmsg");
{
if (rdlReasoncodeType.SelectedIndex == 0|| rdlReasoncodeType1.SelectedIndex== -1)
{
if (rdlReasoncodeType1.SelectedItem == null)
{
if (sum == 0)
{
lbldlmsg.Text = "*Approve fields are mandatory to check";
return; }}}}
else
{
sum++;
lbldlmsg.Text = "";
}
lbldlmsg.Text = "";
}}
I'm trying to change the colour based on the value in the cell, complete or incomplete but for some reason it's saying that 'Color' doesn't exist in the current context.
Is there a system item I should be using or something?
If anyone has any alternatives to what I'm trying to do that would also be appreciated.
foreach (DataGridViewRow row in dtaFinished.Rows)
{
string RowType = row.Cells[4].Value.ToString();
if (RowType == "Completed")
{
row.DefaultCellStyle.BackColor = Color.Green; //Error on these lines
row.DefaultCellStyle.ForeColor = Color.White; //Error on these lines
}
else if (RowType == "Incomplete")
{
row.DefaultCellStyle.BackColor = Color.Yellow;
row.DefaultCellStyle.ForeColor = Color.Black;
}
}
use the below namespace:
using System.Drawing;
hope thiS will help.
Hi You can found your answere Here
I used this in a project a while back :-
private void dgvOutstandingReports_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int colIndex = e.ColumnIndex;
int rowIndex = e.RowIndex;
if (rowIndex >= 0 && colIndex >= 0)
{
DataGridViewRow theRow = dgvOutstandingReports.Rows[rowIndex];
if (theRow.Cells[colIndex].Value.ToString() == "Daily Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightYellow;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Monthly Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightGray;
}
else if (theRow.Cells[colIndex].Value.ToString() == "SMP Report")
{
theRow.DefaultCellStyle.BackColor = Color.Snow;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Weekly Report")
{
theRow.DefaultCellStyle.BackColor = Color.Pink;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Hourly Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightSteelBlue;
}
}
}
I came up with this code, which I thought was rather clever (the requirement is that if the selected date is in the past, the TextBoxes should be readonly, otherwise (today's date or a future date) they should be editable):
bool? setReadOnly = null;
if (SelectedDateIsInThePast() && (!currentlyReadOnly)) {
setReadOnly = true;
} else if (!SelectedDateIsInThePast() && (currentlyReadOnly)) {
setReadOnly = false;
}
if (setReadOnlyToTrue.HasValue) {
foreach (Control ctrl in tableLayoutPanelPlatypus.Controls) {
if (ctrl is TextBox) {
tb = (TextBox)ctrl;
tb.ReadOnly = setReadOnlyToTrue.Value;
}
}
}
...but find that nullable bools are "data type non grata" among my compadres.
Is there a non-complicated way to do the same thing (only loop through the controls if the readonly value needs to be changed?). Of course, I could simply set them regardless of whether they needed to be set this way:
if (SelectedDateIsInThePast()) {
setReadOnly = true;
} else {
setReadOnly = false;
}
foreach (Control ctrl in tableLayoutPanelPlatypus.Controls) {
if (ctrl is TextBox) {
tb = (TextBox)ctrl;
tb.ReadOnly = setReadOnly;
}
}
...but I don't like to perform moot operations, if it's reasonably possible to avoid them.
Factor the loop into a method, and only call the method in the cases you set setReadOnly:
if (SelectedDateIsInThePast() && (!currentlyReadOnly)) {
SetReadOnly(true);
} else if (!SelectedDateIsInThePast() && (currentlyReadOnly)) {
SetReadOnly(false);
}
You can use |=, &=, and two non-nullable booleans to implement the same requirement:
bool forceReadOnly = SelectedDateIsInThePast() && (!currentlyReadOnly);
bool clearReadOnly = !(!SelectedDateIsInThePast() && (currentlyReadOnly));
foreach (Control ctrl in tableLayoutPanelPlatypus.Controls) {
if (ctrl is TextBox) {
tb = (TextBox)ctrl;
tb.ReadOnly |= forceReadOnly;
tb.ReadOnly &= clearReadOnly;
}
}
I think a nullable bool is fine... but another way would be:
public enum ControlState
{
Unknown = 0,
DateInPast,
DateInFuture
}
....
var state = ControlState.Unknown;
if (SelectedDateIsInThePast() && (!currentlyReadOnly)) {
state = ControlState.DateInPast;
} else if (!SelectedDateIsInThePast() && (currentlyReadOnly)) {
state = ControlState.DateInFuture;
}
if (state != ControlState.Unknown) {
foreach (Control ctrl in tableLayoutPanelPlatypus.Controls) {
if (ctrl is TextBox) {
tb = (TextBox)ctrl;
tb.ReadOnly = setReadOnlyToTrue.Value;
}
}
}
Use an enum with three separate, meaningful states ?
enum ShouldSetState
{
No,
SetReadOnly,
SetReadable
}
Then do
ShouldSetState setState = ShouldSetState.No;
if (SelectedDateIsInThePast() && (!currentlyReadOnly)) {
setState = ShouldSetState.SetReadOnly;
} else if (!SelectedDateIsInThePast() && (currentlyReadOnly)) {
setState = ShouldSetState.SetReadable;
}
if (setState != ShouldSetState.No) {
foreach (Control ctrl in tableLayoutPanelPlatypus.Controls) {
if (ctrl is TextBox) {
tb = (TextBox)ctrl;
tb.ReadOnly = setState == ShouldSetState.SetReadOnly;
}
}
}
Your code could be made more consise without using a nullable bool:
bool inThePast = SelectedDateIsInThePast();
if (currentlyReadOnly != inThePast )
{
currentlyReadOnly = inThePast;
foreach(var tb in tableLayoutPanelPlatypus.Controls.OfType<TextBox>())
tb.ReadOnly = currentlyReadOnly;
}
Also, if you have to do a lot of these types of UI manipulations, you might consider data binding.