Find Textbox control - c#

In my application i have 50 textboxes i want find all the textbox control using the code and i want to perform a color change in the textbox after doing certain validations. How can i acheive that? i used the following code but it doesnt work properly
foreach (Control cntrl in Page.Controls)
{
if (cntrl is TextBox)
{
//Do the operation
}
}
<%# Page Language="C#" MasterPageFile="~/HomePageMaster.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="Default" Title="Sample Page" %>

I've recently started doing this the 'modern' LINQ way. First you need an extension method to grab all the controls of the type you're interested in:
//Recursively get all the formControls
public static IEnumerable<Control> GetAllControls(this Control parent)
{
foreach (Control control in parent.Controls)
{
yield return control;
foreach (Control descendant in control.GetAllControls())
{
yield return descendant;
}
}
}`
Then you can call it in your webform / control:
var formCtls = this.GetAllControls().OfType<Checkbox>();
foreach(Checkbox chbx in formCtls){
//do what you gotta do ;)
}
Regards,
5arx

protected void setColor(Control Ctl)
{
foreach (Control cntrl in Ctl.Controls)
{
if (cntrl.GetType().Name == "TextBox")
{
//Do Code
}
setColor(Control cntrl);
}
}
You can then call this with setColor(Page)

This one goes recursively, so it will run on all controls in the page.
Note that if you want it to go over the textboxes in the databound controls too, you should probably call it in the OnPreRender.
protected void Page_Load(object sender, EventArgs e)
{
ColorChange(this);
}
protected static void ColorChange(Control parent)
{
foreach (Control child in parent.Controls)
{
if (child is TextBox)
(child as TextBox).ForeColor = Color.Red;
ColorChange(child);
}
}

You will probably have to recursively go through each container. This article has one method of doing it.

Related

Multiple Textbox Validations

So I have a form with many TextBox-es which all need to be filled in. I have researched textbox validation but I can only find instructions for validating singular text boxes. Below is the code I have for the singular textbox validation. I was just wondering if it possible to hit all of them at once instead of this for each one. Any help would be much appreciated!
private void txtName_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text.Trim()))
{
epName.SetError(txtName, "Name is required.");
}
else
{
epName.SetError(txtName, string.Empty);
}
}
Assuming you are using WinForms
// Get all the controls of the forms
var controls = this.Controls;
foreach (Control mycontrol in controls)
{
// Check if the Control is a TextBox
if (mycontrol is TextBox)
{
//Perform Operation
}
}
var controls = this.Controls;
foreach (Control mycontrol in controls)
{
// Check if the Control is a TextBox
if (mycontrol is TextBox)
{
epname.seterror(mycontrol, mycontrol+"is required");
}
}

Iterating through checkboxes inside different panels that are inside a parent panel

So I am making a "Disable all checked checkboxes" button for my windows form application in c#. The code I have works fine when set to loop through a specific panel, like so:
private void LockChecked_Click(object sender, EventArgs e)
{
foreach (Control c in block1Panel.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
if (cb.Checked == true)
{
cb.Enabled = false;
}
}
}
}
But what I'd like to do is loop through all the block panels (block1Panel, block2Panel, block3Panel, etc.) that are inside a main panel (Assignments_Panel).
So, how can I iterate through all the checkboxes from all panels, without having to write a loop for each panel? I know it's possible, but since I'm only a beginner I'm not able to figure this one out, even after hours of searching...
Thank you in advance! And if anything in my question is unclear please say so, so I can explain further!
This method may help. It loops through each control from a parent control, which in your case looks as tough it'd be Assignments_Panel, then for each control that belongs to the parent control, it will either loop through all child controls again, or disable the control, if it is a checkbox.
private void DisableCheckboxes(Control parentControl)
{
foreach (Control childControl in parentControl.Controls)
{
if (childControl is Panel childPanel)
{
DisableCheckboxes(childPanel);
}
else if (childControl is CheckBox childCheckBox)
{
childCheckBox.Enabled = false;
}
}
}
Well, we can enumerate all the controls within form while checking if the control is of type CheckBox; there are many implmentations for this, say
How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
let's write good old Bread First Search (no Linq, recursion etc.)
private void LockChecked_Click(object sender, EventArgs e) {
Queue<Control> agenda = new Queue<Control>(new [] { this });
while (agenda.Count > 0) {
Control control = agenda.Dequeue();
if (control is CheckBox cb && cb.Checked)
cb.Enabled = false;
foreach (Control child in control.Controls)
agenda.Enqueue(child);
}
}

How to change the properties of controls of a usercontrol at runtime in C#?

I am a novice to C#.
My application contains Main form and a few usercontrols.
I want the usercontrol named "uc_MainMenu" to be displayed in the panel named "panel2" inside the Main form when I start running the applicaiton.
uc_MainMenu obj_uc_MainMenu = new uc_MainMenu();
private void frmMain_Load(object sender, EventArgs e)
{
this.panel2.Controls.Add(obj_uc_MainMenu);
}
It works.
uc_MainMenu contains a few buttons: btnHeadmaster,btnTeacher,btnStudent,btnAttendance,btnExam and btnLogin.
Each of those buttons' click will bring the corresponding predefined usercontrols.
Here is my question.
I want to disable all the buttons except btnLogin when the form loads.
How can I do that?
I tried this way but it didn't work.
foreach (Control ctrl in panel2.Controls)
{
if (ctrl.GetType() == typeof(Button))
{
((Button)ctrl).Enabled = false;
}
}
I can change each button's enabled properties in the uc_MainMenu, but if so I will have to change them again whenever I switch the usercontrols. That's why I left their enabled property to true when I designed the usercontrols.
Try this:
foreach (Control ctrl in obj_uc_MainMenu.Controls)
{
if (ctrl.GetType() == typeof(Button) && ((Button)ctrl).Name != "btLogin")
{
((Button)ctrl).Enabled = false;
}
}
Notice that I changed panel2 by obj_uc_MainMenu.
Create a property inside user control :
public bool MyButtonEnabled
{
get
{
return anyButtonButNo_btLogin.Enabled;
}
set
{
foreach (Control ctrl in this.Controls)
{
if (ctrl.GetType() == typeof(Button) && ((Button)ctrl).Name != "btLogin")
{
((Button)ctrl).Enabled = value;
}
}
}
}
Now you can use this property anywhere that usercontrol used.
uc_MainMenu obj_uc_MainMenu = new uc_MainMenu();
private void frmMain_Load(object sender, EventArgs e)
{
this.panel2.Controls.Add(obj_uc_MainMenu);
///this property will access the button inside that user control
obj_uc_MainMenu.MyButtonEnabled=false;
}
If your buttons is inside the obj_uc_MainMenu, then you can not retrieve it via panels.Controls. If you want to retrieve them, you should use obj_uc_MainMenu.Controls.
I don't know how did you define the user control obj_uc_MainMenu, then I guest you can do something like this:
foreach (Control ctrl in obj_uc_MainMenu.Controls)
{
if (ctrl.GetType() == typeof(Button))
{
((Button)ctrl).Enabled = false;
}
}
Find will find the panel. If it exists, then iterate through the usercontrol for type button and modify the button/s properties. No need of casting for button within foreach loop (we know its of type Button).
// Get the panel
var panel2 = Controls.Find("YourPanel", true).FirstOrDefault() as Panel;
// If it exists
if (panel2 != null)
{
foreach (var button in panel2.obj_uc_MainMenu.Controls.OfType<Button>())
{
// Set the value of each one
button.Enabled = false;
}
}

Forms : Enabled/Disable all controls in a container (panel)

I am coding a C# Forms application and would like to know how to enable/disable all controls container within a panel.
Here is my code:
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (var item in panel.Controls)
{
item.enabled = enabled;
}
}
There is no enabled property in the panel.Controls collection.
How can I enable/disable all controls container within a panel.
Thanks in advance.
You are getting controls as var and iterating on them and var doesn't contain any property Enabled. You need to loop through controls and get every control as Control. Try this
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (Control ctrl in panel.Controls)
{
ctrl.Enabled = enabled;
}
}
Enabled can be true or false.
"How can I enable/disable all controls container within a panel."
A:
If you want to disable or enable all controls within a panel, you can directly call,
Panel panel;
-> panel.Enabled = true;//For enabling all controls inside the panel.
-> panel.Enabled = false;//For disabling all controls inside the panel.
If you want only specific controls inside the panel to be enabled or disabled then you can iterate through the collection of controls and set it's enable state to true or false based on your requirement.
If you declare item as var (in the foreach loop), it won't have the properties of a windows control.
You should declare it as a control.
Try this code snippet and it should work:
foreach (Control item in panel.Controls)
{
item.Enabled = true; // = true: enable all, = false: disable all
}
Try the following code,
private void DisableAll_Click(object sender, EventArgs e)
{
EnabledPanelContents(this.panel1, false);
}
private void EnabledPanelContents(Panel panel, bool enabled)
{
foreach (Control item in panel.Controls)
{
item.Enabled= enabled;
}
}
#anshu
if your controls are HTML controls then use
foreach (Control ctrl in myControl1.Controls)
if (ctrl is HtmlControl)
((HtmlControl)ctrl).Disabled = true;
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control item in panel.Controls)
if (ctrl is Button)
((Button)item).Enabled = false;
}

how to use foreach loop to edit textboxes

foreach(textbox t in this.controls)
{
t.text=" ";
}
I want to clear all the textboxes in my page at one time.
I am getting an error:
Unable to cast object of type 'System.Web.UI.LiteralControl' to type
'System.Web.UI.WebControls.TextBox'.
The error is because your controls collection doesn't only contain text boxes. Try this instead.
foreach (Control c in this.Controls)
{
TextBox t = c as TextBox;
if (t != null)
{
t.text=" ";
}
}
You are going through the controls, and not all controls are necessarily textboxes, so the foreach loop cannot be compiled.
The straightforward approach is to do a foreach (Control c in this.Controls) and then check whether the control is a textbox.
You can also try this in later versions of .NET:
foreach(TextBox t in this.Controls.OfType<TextBox>())
Your page probably has child controls that has child controls too. Therefor the best way to do this is with recursion. I have written a function that reset all my controls for a certain page, panel or other control I define as the parent.
/// <summary>
/// Resets all the controls in a parent control to their default values.
/// </summary>
/// <param name="parent">Parent of controls to reset</param>
protected void ResetChildControls(Control parent)
{
if (parent.Controls.Count == 0)
return;
foreach (Control child in parent.Controls)
{
if (child is TextBox)
{
((TextBox)child).Text = "";
}
else if (child is HiddenField)
{
((HiddenField)child).Value = "";
}
else if (child is DropDownList)
{
DropDownList dropdown = (DropDownList)child;
if (dropdown.Items.Count > 0)
{
dropdown.SelectedIndex = 0;
}
}
else if (child is RadioButton)
{
((RadioButton)child).Checked = false;
}
else if (child is RadioButtonList)
{
RadioButtonList rbl = (RadioButtonList)child;
rbl.SelectedIndex = rbl.Items.Count > 0 ? 0 : -1;
}
else if (child is CheckBox)
{
((CheckBox)child).Checked = false;
}
else if (child is CheckBoxList)
{
CheckBoxList cbl = (CheckBoxList)child;
cbl.ClearSelection();
}
else if (child is DataGrid)
{
((DataGrid)child).SelectedIndex = -1;
}
ResetChildControls(child);
}
}
Based on the code that has already been posted on this page I would say the final piece of code to achieve what you asked (reset all text controls on a page) would look like:
protected void ResetTextBoxes(Control parent)
{
if(parent is TextBox)
{
((TextBox)parent).Text = string.Empty;
}
foreach(Control child in parent.Controls)
{
if (child is TextBox)
{
((TextBox)child).Text = string.Empty;
}
ResetTextBoxes(child);
}
}
This method can be used on any control or group of controls to reset all child textboxes. It takes into account:
The control passed (parent) may by a TextBox
That only textboxes being reset was requested in the original question
That the user hasn't specified if linq is allowed
That the control may have child controls.
You could use this like so:
ResetTextBoxes(this); // reset all TextBox's on a page
ResetTextBoxes(somePanel); // reset all TextBox's within a single <asp:Panel>
Other Options
Other options to reset textbox controls are:
Issue a Response.Redirect("~/ThisPageUrl.aspx"); to reload the current page
Disable viewstate on either the page or individual controls so that its state is lost after postback
using LINQ:
foreach (TextBox t in this.Controls.Where(c => c is TextBox))
{
//...
}

Categories