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: