Reputation: 5058
private void btnSaveInformation_Click(object sender, EventArgs e)
{
foreach (Control child in Controls)
{
if (child is TextBox)
{
TextBox tb = child as TextBox;
if (string.IsNullOrEmpty(tb.Text))
{
tb.Text = @"N/A";
}
}
}
//var bal = new StudentBal
//{
// FirstName = txtFirstName.Text
//};
//bal.InsertStudent(bal);
}
What I want to achieve is for the system to check if there is any blank checkbox, and I have numerous in the form, and if it is blank, then assign a value of "N/A". What am I doing wrong with the codeI have? Thank you.
Upvotes: 0
Views: 1854
Reputation: 16956
I see nothing wrong in your code. I suspect controls that you are looking are nested controls.
I would suggest flatten the hierarchy and get all the (nested)controls and then look for specific type.
static Func<Control, IEnumerable<Control>> GetControls =
(control) => control
.Controls
.Cast<Control>().SelectMany(x => GetControls(x))
.Concat(control.Controls.Cast<Control>());
Now you could use the above delegate in your code like shown below.
foreach (TextBox tb in GetControls(this).OfType<TextBox>())
{
if (string.IsNullOrEmpty(tb.Text))
{
tb.Text = @"N/A";
}
}
Upvotes: 0
Reputation: 201
Are the textboxes placed in panels or other grouping controls? If so, the form's Controls collection would not contain references to them; they would only contain the immediate children (which would be the panels, etc.)
If they are contained within a group control or panel, you would want to do something like this instead:
foreach (Control child in myGroupPanel.Controls)
{
if (child is TextBox) { // your additional code here }
}
If you want a more robust method, the following show different ways of getting a list of all controls:
How to get all children of a parent control?
How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
Upvotes: 2
Reputation: 29006
You could use child.GetType()
to get the type of the control while iterating the group of controls, then compare the same with the typeof(TextBox)
with will help you to filter textBoxes from the control collection. try this:
foreach (Control child in Controls)
{
if (child.GetType() == typeof(TextBox))
{
TextBox tb = (TextBox)child;
if (string.IsNullOrEmpty(tb.Text))
{
tb.Text = @"N/A";
}
}
}
Or else you can use iterate through filtered collection like the following(assuming that Controls
is a collection of controls):
foreach (Control child in Controls.OfType<TextBox>().ToList())
{
TextBox tb = (TextBox)child;
if (string.IsNullOrEmpty(tb.Text))
{
tb.Text = @"N/A";
}
}
Upvotes: 0