Iterating through textboxes using asp.net - c#

I am building a page with asp.net. I have a form with a table that contains TextBoxes and a submit button. When the form is submitted, I want to grab all the text that was entered into the TextBoxes and operate on them. To do this, I have the following method:
protected void Button1_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (Control c in this.Controls)
{
if (c.GetType().Name == "TextBox")
{
TextBox tb = (TextBox)c;
sb.AppendLine(tb.Text);
}
}
Label1.Text = sb.ToString();
}
The problem with this is that the controls apparently doesn't include any of my textboxes. When I iterate through the controls and print out their names, the only one I get is "site_master." (I also tried Controls and Page.Controls instead of this.Controls).
Is there something wrong with my iterator? Is there another way in which I could iterate through all of the textboxes in the table or page? What is the best way to accomplish this?

Would it be too much to build a List<Textbox>, given you know all your textbox controls?
List<Textbox> txtBoxes = new List<Textbox>();
txtBoxes.Add(tb1);
txtBoxes.Add(tb2);
//etc..
Then you have a nice list to work with

If I knew the controls were all in a given containing control, I would simply poll the controls of that control. For example, this.Form.Controls. However, if they could be nested within other child controls, then you could recursively explore the depths from a common outer container.
private IEnumerable<T> FindControls<T>(Control parent) where T : Control
{
foreach (Control control in parent.Controls)
{
if (control is T)
yield return (T)control;
foreach (T item in FindControls<T>(control))
yield return item;
}
}
So this would allow you to retrieve all TextBox children.
List<TextBox> textBoxes = this.FindControls<TextBox>(this).ToList();
string output = string.Join(",", textBoxes.Select(tb => tb.Text));

I'm going to assume that you are using web forms ASP.NET. Typically you declare your controls on the aspx page using something similar to
<asp:TextBox ID="someId" runat="server/>
If you have done this then in your code behind your should just be able to reference the variable someId and the property Text to get/set the text in the control.
If you are building the controls dynamically on the server you should be able to stick them in a list and iterate through it. Make sure you are creating the controls and adding them to the table during the correct part of the page lifecycle. When you add them to a cell in the table you could also keep a reference to the control in a list and just enumerate through that list in your event handler.
Maybe something along the lines of (I didn't compile this so there are probably issues):
public class MyPage: Page
{
private List<TextBox> TxtBoxes = new List<TextBox>();
//registered for the preinit on the page....
public void PreInitHandler(object sender, EventArgs e)
{
for(var i = 0; i < 2; i++)
{
var txtBox = new TextBox{Id = textBox+i};
//...add cell to table and add txtBox Control
TxtBoxes.Add(txtBox);
}
}
}

Related

How to access the controls in the TabPage of a TabControl

I have two Buttons in my Form and two TextBoxes inside a TabControl.
I'm not sure how I can save to the Clipboard the text of the TextBoxes using the Buttons.
To do this, we tried to assigned the same AccessibleName to the controls.
I worked on the code but I do not know how to access the TabPages of the TabControl.
Finally, does someone know of a better way to do that?
public partial class Form1 : Form
{
private void SaveNumBot(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c.AccessibleName == ((Control)sender).AccessibleName)
{
if (c is TextBox)
{
Clipboard.SetDataObject(c.Text);
}
}
}
}
Use pattern matching:
if (c is TextBox textBox)
{
Clipboard.SetDataObject(textBox.Text);
}
You could modify your foreach loop:
foreach(TabPage tabPage in yourTabControl.Controls)
{
foreach (TextBox textBox in tabPage.Controls.OfType<TextBox>().Where(x=>x.AccessibleName == ((Control)sender).AccessibleName))
{
Clipboard.SetDataObject(textBox.Text);
}
}
with this loop you only search for Controls which are from the type Textbox.
Use OfType method to avoid InvalidCastExceptions.
If you have other Controls which inherit from TextBox in your Form I would recommend to add the line x.GetType()==typeof(TextBox) to the Where() method.
With the Where() method we only choose the items which have to same AccessibleName like our sender.
But if you have more textboxes with the same AccessibleName, this loop will run through all items and only choose the last text.
In this case i would recommend:
Clipboard.SetDataObject(yourTabPage.Controls.OfType<TextBox>()
.Where(x=>x.AccessibleName ==((Control)sender).AccessibleName))
.ToList()
.FirstOrDefault().Text);
Here we are going to have 1 text from the first texbox found in the Control. you could also select the Last()entry.

get text of a selected dynamically textbox c#

I have on my winform an usercontrol and I create multiple usercontrols at every button click(at runtime).My usercontrol has an textbox. Also,on winform I have a simple textbox . I want ,when I select an usercontrol,the text from the dynamical textbox to appear also in the simple textbox. In my code it says that the textbox from usercontrol is not in the current context. My code:
private void Gettext()
{
int i = 0;
Control[] txt = Controls.Find("txtBox" + i.ToString(), true);//here I search for the dynamical textbox
foreach (Control c in panel1.Controls)
{
if (c is UserControl1)
{
if (((UserControl)c).Selected)
txtSimple.Text= txtBox[0].Text ;
}
i++;
}
I don't know if I understood your question correctly:
The structure of your form looks something like this:
Your form has a Panel panel1 that has many UserControls of the type UserControl1, created on runtime, and one TextBox txtSimple.
Every UserControl has a TextBox named ["txtBox" + i]
on select you want to synchronize texts of txtSimple and TextBox of selected UserControl
Then:
int i=0;
foreach (Control c in panel1.Controls)
{
if (c is UserControl1)
{
if (((UserControl)c).Selected)
{
TextBox dynTxtBox = (TextBox)c.Controls["txtBox" + i];
txtSimple.Text= dynTxtBoxe.Text;
}
}
i++;
}
If you can't find your TextBox this way, it probably means that its name is not set correctly.
Also, if you have only one TextBox on your UserControl then there's normally no need to name it in such a specific way (I mean from your code I assumed you have txtBox0 on your first user control, txtBox1 on your second and so on). You can simply name it "txtBox", then access it like this:
txtSimple.Text = selectedUserControl.Controls["txtBox"].Text;
Control names are unique in a Controls collection of a Control, UserControl and Form.
Control[] txt = ...
txtSimple.Text= txtBox[0].Text ;
May be replace txtBox[0].Text to txt[0].Text ?
Well for a start
Control[] txt = Panel1.Controls.Find("txtBox" + i.ToString(), true)
Then
foreach (Control c in txt) // txt???
{
UserControl1 uc = c as UserControl1;
if (uc != null)
{
if (uc.Selected) txtSimple.Text= uc.Text ;
}
}
Then if if you are are testing for UserControl1, you should also cast to UserControl1 not UserControl
UserControl1 is an extremely bad name for it..
I'm not even going to mention the assumption that all controls have a name starting with txtBox and that no other controls have...
And the entire thing dies if more than one control is selected when it runs.
you need to have a Selected event on your UserControl.
//in UserControl
public event EventHandler Selected;
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
if(Selected!=null)
Selected(this,null);
}
now subscribe to Selected event of UserControl when you dynamically create it. Like this:
UserControl control = new UserControl();
control.Selected += myControl_Selected;
private void myControl_Selected(object sender, EventArgs e)
{
UserControl control = (UserControl)sender;
textBox2.Text = control.Text;
}
I hope this helps.

Gathering textboxes created in design

I added several textboxes by drag_n_dropping. Now I want to gather them all under a textbox array. I know how to create array of textboxes in code but not how to gather the textboxes created during design. Could anyone help please?
Sometimes the textboxes are not placed on the form directly but on a container control like a tab control or a split container. If you want to find all these textboxes, a recursion will help
private List<TextBox> _textboxes = new List<TextBox>();
private void GetTextBoxes(Control parent)
{
foreach (Control c in parent.Controls) {
var tb = c as TextBox;
if (tb != null) {
_textboxes.Add(tb);
} else {
GetTextBoxes(c);
}
}
}
Then you call GetTextBoxes by passing the form as argument
GetTextBoxes(this);
This is possible, since Form itself derives from Control.
This assumes your TextBoxes are within same GroupBox or Panel.
var groupOfTextBoxes = groupBox1.Controls.OfType<TextBox>();
MessageBox.Show(groupOfTextBoxes.Count().ToString());
var textBoxesWithinForm = this.Controls.OfType<TextBox>();
MessageBox.Show(textBoxesWithinForm.Count().ToString());
Requires using System.Linq;. Please note that textBoxesWithinForm will ignore TextBoxes that are within groupBox and vice versa.
Or like #Jeff suggests but instead of going thru this.Controls and comparing if Control is Textbox:
foreach (TextBox in this.Controls.OfType<TextBox>())
{
//add to your array
}
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
//add to your array
}
}

empty textbox controls after the data is inserted / saved/ submitted in a c# winform application

I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:
textbox1.Text="";
But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?
Please guide.
Try this
foreach(TextBox textbox in this.Controls.OfType<TextBox>())
{
textbox.Text = string.Empty;
}
If you want recursivly clear all textboxes use this function.
void ClearTextBoxes(Control control)
{
foreach(Control childControl in control.Controls)
{
TextBox textbox = childControl as TextBox;
if(textbox != null)
textbox.Text = string.Empty;
else if(childControl.Controls.Count > 0)
ClearTextBoxes(childControl);
}
}
If you have all the textboxes on a form without panels or group boxes, you can do this:
foreach (var conrol in Controls)
{
var textbox = conrol as TextBox;
if (textbox != null)
textbox.Clear();
}
If you have a panel, use panel.Controls instead.
You could use the Linq API described in the following article:
http://www.codeproject.com/KB/linq/LinqToTree.aspx#linqforms
This allows you to apply Linq-to-XML style queries on Windows Forms. The following will clear all the TextBox controls that are descendants of 'this':
foreach(TextBox textbox in this.Descendants<TextBox>()
.Cast<TextBox>())
{
textbox.Text = string.Empty;
}
If you want to clear everything on the form, I would suggest a pair of utility function such as:
public static void ClearAllControls(Control.ControlCollection controls)
{
foreach (var control in controls)
ClearAllControls(control);
}
public static void ClearAllControls(Control control)
{
var textBox = control as TextBox
if (textBox != null)
{
textBox.Text = null;
return;
}
var comboBox = control as ComboBox;
if (comboBox != null)
{
comboBox.SelectedIndex = -1;
return;
}
// ...repeat blocks for other control types as needed
ClearAllControls(control.Controls);
}
Call the first method, passing the form's Controls collection, and it will recursively drill down through panels, groups, etc, clearing all the controls it knows about. You'll have to add a block for each different control type, but at least you only have to do it once. It's a bit brute-force, but it's not the kind of code that ends up running in a loop, and it runs plenty fast, anyway.
The final line, which does the recursion, will only be reached if the current control being worked on hasn't already proven to be one of the known types, so you don't have to worry about accidentally "drilling into" things like TextBoxes, looking for child controls that won't be there.

Adding a user control to a page programatically while preserving controls already present

I am trying to add a user control into a div at runtime. I can add the control no probelem but it overwrites the previous control added.
Basically, I am trying to add passengers to a travel system - the passenger details are in the user control and I don't know in advance how many there will be. I have an add new passenger button which should append the new user control into the div without overwriting the previous passenger.
The code is c#/.net 4.
I have tried to save the control data into viewstate and re add it with the new one but that also doesn't work. Here is a snippet of the code I'm using
foreach (Control uc in p_passengers.Controls) {
Passenger p = uc as Passenger;
if (p != null) {
p.SaveValues();
}
}
however, p.SaveAs() (just writes the control values into ViewState) is never hit.
Im sure its just something stupid but any ideas??
Cheers guys.
Are you re-creating all of your dynamic controls for every postback?
Remember each postback is a new instance of the Page class and any controls you previously created will need to be explicitly re-created.
Update
If you had a list of added items in viewstate, something like this..
private List<string> Items
{
get
{
return ViewState["Items"] = (ViewState["Items"] ?? new List<string>());
}
}
Then in your click handler you could simply add to this list :
private void btn_Click(object sender, EventArgs e)
{
this.Items.Add("Another Item");
}
Then override CreateChildControls
protected overrides CreateChildControls()
{
foreach (string item in this.Items)
{
Passanger p = new Passenger();
p.Something = item;
this.p_passengers.Controls.Add(p);
}
}

Categories