How can I get all TextBoxes inside of a Custom UserControl? - c#

I need a way to dynamically gather all of the TextBoxes inside of a custom UserContorl in ASP.net WebForms, server-side
I thought this would work:
foreach (var control in Page.Controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
// stuff here
}
}
But it doesn't do what I thought it would, and I don't see how else to get that information.
So, how can I dynamically get all of the textboxes on the server-side of a custom UserControl in ASP.net webforms?

You need a recursive method, because not all level 1 children are necessarily text boxes (depends on the control/container hierarchy in your user control):
private IEnumerable<TextBox> FindControls(ControlCollection controls)
{
List<TextBox> results = new List<TextBox>();
foreach(var control in controls)
{
var textBox = control as TextBox;
if (textBox != null && textBox.MaxLength > 0)
{
results.Add(textBox);
}
else if(textBox == null)
{
results.AddRange(FindControls(control.Controls));
}
}
return results;
}
After you get the results you can iterate them and do whatever you need to do.

Looks like recursive is the way to go:
foreach (Control control in Page.Controls)
{
DoSomething(control);
}
// And you need a new method to loop through the children
private void DoSomething(Control control)
{
if (control.HasControls())
{
foreach(Control c in control.Controls)
{
DoSomething(c);
}
}
else
{
var textBox = control as TextBox;
if (textBox != null)
{
// Do stuff here
}
}
}

Related

Make multiple Textboxes visible or invisible using for loop

In my form I've 50 textboxes in visible=false state, when a user enter particular number , those many textboxes should be displayed and the remaining textboxes should remain in visible false state.
Should end up looking something like this:
foreach (var control in this.Controls)
{
var textbox = control as TextBox;
if (var != null) textbox.Visible = true;
}
You can loop throug all textbox controls like this:
foreach (Control item in this.form1.Controls)
{
System.Web.UI.HtmlControls.HtmlInputText tbx = item as System.Web.UI.HtmlControls.HtmlInputText;
if (tbx!= null)
{
if(tbx.Text == "some text")
tbx.Visible = false; // or true how ever you want it
else
tbx.Visible = true;
}
}
So if tbx is not null, item is textbox, actually:
<input type="text"/>
You can do this same trick with other HtmlControls.
Change form1 to that form you, which controls you want to loop through.
You can wrap all your control inside a Asp.net Panel Control.
int counter = 0;
int numberOfTextBoxtoShow = 4; // set by user
foreach (Control c in Panel1.Controls)
{
if (c is TextBox)
{
if (counter < numberOfTextBoxtoShow)
{
c.Visible = true;
counter++;
}
else c.Visible = false;
}
}

Trying to find controls

I want to add runat=server dynamically to a CheckBoxList so that it can be found by FindControl.
CheckBoxList cbl = new CheckBoxList();
cbl.ID = "cbl" + intQuestionCount.ToString();
// get choices from choice list
int intChoiceListId = Convert.ToInt32(detail.ChoiceListID);
var choiceList = (from cl in _svsCentralDataContext.SVSSurvey_ChoiceListItems
where cl.ChoiceListID == intChoiceListId
orderby cl.Description
select cl);
cbl.DataSource = choiceList;
cbl.DataTextField = "Description";
cbl.DataBind();
cbl.Visible = true;
cbl.CssClass = "PositionCol3";
questionsPanel.Controls.Add(cbl);
I have 2 recursive find control methods:
private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase)
&& childControl is HtmlControl
)
{
return (HtmlControl)childControl;
}
if (childControl.HasControls())
{
HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
if (result != null)
{
return result;
}
}
}
return null;
}
private WebControl FindWebControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase)
&& childControl is WebControl
)
{
return (WebControl)childControl;
}
if (childControl.HasControls())
{
WebControl result = FindWebControlByIdInControl(childControl, id);
if (result != null)
{
return result;
}
}
}
return null;
}
The screen is initially created dynamically (if !isPostback), based on an SQL record. The FindControl methods are used after this lot has been displayed, when the user clicks the 'Save' button.
Neither Find control method finds my CheckBoxList!!
You are adding controls through your code behind, they are already server side controls, you don't have to add runat="server". You are not finding them properly.
Make sure they are added to the page before you look for them.

"Unable to cast object" while looping through programatically created textboxes

I have some Textboxes that are created dynamically --
int i = 1;
while (reader.Read())
{
System.Web.UI.WebControls.TextBox textBox = new System.Web.UI.WebControls.TextBox();
textBox.ID = reader["field_id"].ToString();
textBox.Enabled = false;
HtmlGenericControl div = new HtmlGenericControl("div");
if(i%2 != 0)
div.Attributes.Add("style", "margin-right:120px;padding-bottom:20px;");
if (i % 2 == 0)
div.Attributes.Add("style", "padding-bottom:20px;");
div.Attributes.Add("class", "inline fourcol");
div.InnerHtml = "<label>" + reader["field"] + "</label>";
div.Controls.Add(textBox);
panelId.Controls.Add(div);
textBox.Text = reader["field_value"].ToString();
++i;
}
That works fine (at least i'm sure -they show up how they should). But when i try to loop through them to enable them, or get their values, i get an "Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'. " error.
This is how i've been trying to do it --
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (System.Web.UI.WebControls.TextBox t in panel.Controls)
{
t.Enabled = true;
}
}
Thanks!
You're looping over panel.Controls, which will loop over every control in the panel. This is not necessarily the same thing as looping over everything you've added. If there was something else inside the panel that existed when you started, you will end up getting that too.
What you probably wanted was this:
foreach (var t in panel.Controls.OfType<System.Web.UI.WebControls.TextBox>())
{
t.Enabled = true;
}
You are putting each textbox inside a "div" control which is HtmlGenericControl, then inside the panel control. So first you must search for the HtmlGenericControl inside panelId.Controls
A sample code that might help you:
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (Control c in panelId.Controls)
{
if (c is HtmlGenericControl)
{
foreach (var textbox in c.Controls.OfType<TextBox>()) //ofType returns IEnumerable<TextBox>
textbox.Enabled = true;
}
}
}
There is a control inside your Panel, that is not a TextBox and could not be cast to it. You should place a breakpoint before the loop and check the panel.Control collection contents in debug mode.
You can avoid the issue if you don't specify a type in the foreach loop and do the safe cast yourself.
foreach (var t in panel.Controls)
{
var textbox = t as System.Web.UI.WebControls.TextBox;
if(textbox != null)
{
textbox.Enabled = true;
}
}
You should check if control is TextBox
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var t in panel.Controls)
{
if (t is System.Web.UI.WebControls.TextBox)
((System.Web.UI.WebControls.TextBox)t).Enabled = true;
}
}
The Controls collection will contain a collection of all the controls in the panel - not just TextBoxes. You can iterate through all of the controls and use the as operator to perform a type cast. If the type cast succeeds then you may enable the textbox.
public void EditPanel(System.Web.UI.WebControls.Panel panel)
{
foreach (var control t in panel.Controls)
{
System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox;
if (textBox != null)
{
control.Enabled = true;
}
}
}
you add the textbox to the div element and the div element to the panel. therefore you need to select the controls in the panel and then find the textbox.
foreach (var t in panel.Controls.Cast<Control>().SelectMany(c => c.Controls))
{
if (t is TextBox == false) continue;
((TextBox)t).Enabled = true;
}

Using a foreach loop to retrieve TextBox's within a GroupBox

I have ten group boxes in a WinForm. Each group box contains 10 text boxes, and I have defined each TextBox name. How can I get each text box using a foreach loop?
foreach(Control gb in this.Controls)
{
if(gb is GroupBox)
{
foreach(Control tb in gb.Controls)
{
if(tb is TextBox)
{
//here is where you access all the textboxs.
}
}
}
}
But if you have defined each TextBox name
What's the point to get each TextBox by a loop?
You could define a List<TextBox> to hold reference of each TextBox while creating them, then just go though the List to get access of each TextBox.
Here is my suggestion:
foreach(var groupBox in Controls.OfType<GroupBox>())
{
foreach(var textBox in groupBox.Controls.OfType<TextBox>())
{
// Do Something
}
}
Or having it in one loop:
foreach (var textBox in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()))
{
// Do Something
}
try following code,
Control.ControlCollection coll = this.Controls;
foreach(Control c in coll) {
if(c != null)
}
foreach (var ctrl in gbDatabaseColumns.Controls)
{
if (ctrl is DevExpress.XtraEditors.TextEdit)
{
StoreTextEdit(config, (ctrl as DevExpress.XtraEditors.TextEdit));
}
}
foreach (Control txx in groupBox2.Controls)
{
if (txx is TextBox)
txx.Text = "";
if (txx is ComboBox)
txx.Text = "";
// if (txx is DateTimePicker)
// txx.Text = ""; Datetimepicker text can't be erased
}

how to get value of more than one text box in a loop

I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.
Is there any option to work by loop
public IEnumerable<string> AllTextsFromTextboxes()
{
foreach (var control in Page.Controls.OfType<TextBox>())
{
yield return control.Text;
}
}
you can try something on these lines, if all the textbox are on the page directly
foreach(Control c in Page.Controls)
{
if (c is TextBox)
{
//get the text
}
}
This will not work for child controls for that you will have to recursively iterate
yes, you can put your controls in panel and then iterate and get value. e.g.
foreach (Control ctrl in Panel1.Controls)
{
if (ctrl.GetType().Name == "TextBox")
{
if (((TextBox)ctrl).Text != string.Empty)
{
// do stuff here
}
}
}
private void FindSelecedControl(Control control)
{
if (control is TextBox)
{
TextBox txt = (TextBox)control;
txt.Enabled = false;
}
else
{
for (int i = 0; i < control.Controls.Count; i++)
{
FindSelecedControl(control.Controls[i]);
}
}
}
foreach (Control control1 in this.Form.Controls)
{
FindSelecedControl(control1);
}

Categories