Reputation: 1
I have an interesting inquiry for you all.
I am working on a C# project and thought it would make a neat addition to have the textboxes change color if the user submit a non-numeric value. I already have an extended Or conditional statement set up that checks for non-numerics, as such:
public void catchNonNumeric()
{
int parsedValue;
if (!int.TryParse(txtBxStudentInput.Text, out parsedValue) ||
!int.TryParse(txtBxPCInput.Text, out parsedValue) ||
!int.TryParse(txtBxStuTourInput.Text, out parsedValue) ||
!int.TryParse(txtBx203A.Text, out parsedValue) ||
!int.TryParse(txtBx203F.Text, out parsedValue))
{
checker = false;
}
else
{
checker = true;
}
}
But now I am wondering if there is a way to take the failed condition/textbox in this statement and change its color to show the user where exactly the problem is.
This isn't a dire need, just something I think would be cool! Thank you all for the help!
Upvotes: 0
Views: 39
Reputation: 693
The textbox in WPF will get this by default if you bind to a numeric. You will get the data rejection along with UI styling.
Otherwise you can certainly use Func to delegate a query. The Func takes any number of generics as an input and will provide the output you want (in this case a boolean).
var functionDelegate = new Func<string, bool>(text =>
{
int parsedValue;
return int.TryParse(text, out parsedValue);
}
//Usage
var isStudentInputNumercic = functionDelegate(txtBxStudentInput.Text);
Upvotes: 0
Reputation: 37020
One way to do this would be to create a List<TextBox>
of the controls you want to validate, and then loop over them to test the condition. If one of them fails, set the checker
to false
and the ForeColor
of that one to Red
:
public void CatchNonNumeric()
{
// Start our checker flag variable to true
checker = true;
// Create a list of TextBox controls that we want to validate
var textBoxes = new List<TextBox>
{txtBxStudentInput, txtBxPCInput, txtBxStuTourInput, txtBx203A, txtBx203F};
// Validate each TextBox
foreach (var textBox in textBoxes)
{
int parsedValue;
if (int.TryParse(textBox.Text, out parsedValue))
{
// Reset the color to black (or whatever the default is) if it passes
textBox.ForeColor = Color.FromKnownColor(KnownColor.WindowText);
}
else
{
// Otherwise set the color to red and our checker flag to false
checker = false;
textBox.ForeColor = Color.Red;
}
}
}
Upvotes: 1