ASP.net -- Identifying a specific control in code behind - c#

I have a page that holds 5 texboxes each name similar but with a numerial suffix. Example:
tbNumber1, tbNumber2, tbNumber3 and so on.
The reason it's like that is because those textboxes are generated dynamically based on some parameter. I never know how many textboxes will be need for a particular record.
How can I loop trough the text contents of these texboxes?
MY first instinct was to do something like the following, but that obviously does't work :)
for (int i = 0; i <= 3; i++)
{
string foo = tbNumber+i.Text;
//Do stuff
}
Wahts the best way to go trough each of these textboxes?
Thanks!!!

You might be able to do something like this:
for( int i = 0; i < upperLimit; i++ )
{
TextBox control = Page.FindControl("tbNumber" + i) as TextBox;
if( control != null ) {
// do what you need to do here
string foo = control.Text;
}
}

Possibly try something like
foreach(Control control in Page.Controls)
{
//Do stuff
}

If you're generating them dynamically, put them in a List<TextBox> as you generate them:
// in the Page_Load or whereever you generate the textboxes to begin
var boxes = new List<TextBox>();
for (int i = 0; i < numRecords /* number of boxes */; i++) {
var newBox = new TextBox();
// set properties here
boxes.Add(newBox);
this.Controls.Add(newBox);
}
Now you can loop through the textboxes without using crufty string techniques:
foreach (var box in boxes) {
string foo = box.Text;
// stuff
}

What you need is a recursive FindControl like function. Try something like this:
for (int i=0; i<3; i++)
{
Control ctl = FindControlRecursive(Page.Controls, "tbNumber", i.ToString());
if (ctl != null)
{
if (ctl is TextBox)
{
TextBoxControl tbc = (TextBox)ctl;
// Do Something with the control here
}
}
}
private static Control FindControlRecursive(Control Root, string PrefixId, string PostFix)
{
if (Root.ID.StartsWith(PrefixId) && Root.ID.EndsWith(PostFix))
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, PrefixId, PostFix);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}

If you're using a CheckBoxList control you should be able to loop through each checkbox in the control.
foreach(var checkbox in checkboxlistcontrol)
{
string name = checkbox.Text;
}
If you're not using a CheckboxList control, you might want to consider using one as an option.

Related

Variable in C# for loop

I have got many buttons in my Application Form. And I would like to check every buttons text (compare). How can I achive that ?
for (i = 1; i < 30; i++)
{
if (this.button1.Text == "Hello") //here is PROBLEM
{
//..some statement
}
}
So next time this.button1.Text must change to this.button2.Text and so on...
this.button[i].Text not working.
Buttons are not arrays. Each one is a discreet object, and a child of its container.
Ideally, you need to build a collection (array, list, whatever) of the buttons and iterate through that collection, rather than using an index variable (i).
Here's a good approach: https://stackoverflow.com/a/3426721/820068
This is a correct syntax:
foreach (Control button in this.Controls)
{
if (button.GetType() == typeof(Button) && button.Text == "Hello")
{
//..some statement
}
}
I'm quite sure that this is a windows form.
And in windows form you can iterate the controls like this.
foreach (Control c in panel.Controls)
{
string cType = c.GetType().ToString();
// check all buttons
if (cType == "System.Web.UI.WebControls.Button")
{
if(((Button)c).Text == "Hello")
{
}
}
}
So what the code does is to iterate all the controls inside a panel and check each control if it's type is a button.
Update:
As Wesley said, much better approach for the condition is to implement it like this
if (c is Button && c.Text.Equals("Hello")) {
for (int i = 1; i < 3; i++)
{
var buttonName = "button" + i;
Button button = this.Controls.Find(buttonName, true).FirstOrDefault() as Button;
string text = button.Text;
}
try this code.

Iterating through fields?

First of all, I'm not entirely sure how to phrase this or what to search for if someone asked before.
Say I have multiple labels: label1, label2, label3, label4, etc...
Now, I know this works in PHP so I'm wondering if there is a way to do this in C# -
Can I somehow iterate through these labels to set their values in a loop?
i.e.
string[] something = new string[3] { "text", "text", "text" };
for (int i = 0; i < something.length; i++)
{
labels(i).Text = something[i];
}
You can use Controls.Find() method for finding the Label Control by its Control Name.
Try This:
for (int i = 0; i < something.length; i++)
{
((Label) Controls.Find("lablel"+i,true)[0]).Text = something[i];
}
You can get an enumerable list of labels from the Controls collection by using .OfType<>
e.g.
foreach(Label l in this.Controls.OfType<Label>())
{
...
}
Or simply find all the labels without needing to know their names:
foreach (Control ctrl in this.Controls)
{
Label label = ctrl as Label;
if (label != null)
{
label.Text = "";
}
}
You could use Controls.Find to find all references:
for (int i = 0; i < something.length; i++)
{
var lbl = this.Controls.Find("lable" + i, true);
if(lbl.Length > 0)
((Label)lbl[0]).Text = something[i];
}
Another approach using LINQ (which doesn't search recursively as opposed to Find):
for (int i = 0; i < something.Length; i++)
{
Label lbl = this.Controls.Cast<Label>()
.FirstOrDefault(l => l.Name.Equals("lable" + i, StringComparison.InvariantCultureIgnoreCase));
if(lbl != null) lbl.Text = something[i];
}
However, i would not call this good practise. Your array and the labels are directly related to each other. What hapens if you change the array but forget to change the labels?
You should use a different control like ListBox or DataGridView or create the labels dynamically according to the size of the array.

Count the number of controls - C# with the certain names?

C# - 2.0
I am trying to figure out on how to do a loop on a list of controls with certain names: "txtTesting[i]"
txtTesting1
txtTesting2
txtTesting3 ...
txtTesting13
With the code I have a total of 13. But this can change as time goes by. So I am looking to get the data from the textboxes that have data in them. I just can not seem to figure out a way to do a count of the controls. I have tried this...
for (int i = 1; i < 13; i++)
{
if (txtTesting[i].text != "")
{
//
}
}
I am also getting this error...
Error 51 The name 'txtTesting' does not exist in the current context
Unless I am missing something here.
System.Web.UI.WebControls.TextBox
Assuming this is a System.Windows.Forms application, you should be able to go through all your controls on the form and then select the ones that are TextBox as follows:
foreach (System.Windows.Forms.Control control in this.Controls)
{
if (control is System.Windows.Forms.TextBox)
{
if (((System.Windows.Forms.TextBox)control).Text != "")
{
// Do something
}
}
}
For an asp.net application this would be very similar:
foreach (System.Web.UI.Control control in this.Controls)
{
if (control is System.Web.UI.WebControls.TextBox)
{
if ((System.Web.UI.WebControls.TextBox)control).Text != "")
{
// Do something
}
}
}
txtTesting looks like an array. does it have a Length property?
for (int i = 1; i < txtTesting.Length; i++)
if it's a type List<T> than maybe it has a Count property
for (int i = 1; i < txtTesting.Count; i++)
If you don't already have an array, you can initialize one in your presumed Form's constructor
List<WhateverTypeTxtTestingIs> txtTesting = new List<WhateverTypeTxtTestingIs>();
txtTesting.Add(txtTesting1);
txtTesting.Add(txtTesting2);
...
The most efficient way would be to add the controls to an array and loop over that, but you could also loop through the controls and inspect the control's Name:
foreach(Control c in this.Controls) // <-- "this" may not be appropriate - you just need to reference the containing control
{
if(c.Name.StartsWith("txtTesting")
{
///
}
}
In your constructor, after the call to InitializeComponent, stuff the text boxes in a collection.
// class-scoped variable
private List<Textbox> _boxen = new List<TextBox>();
public MyFormDerp()
{
InitializeComponent();
_boxen.Add(txtTesting1);
// etc
_boxen.Add(txtTesting13);
}
and, later on...
foreach(TextBox box in _boxen)
if (box.text != "")
{
//
}
Also, your design should make you itch.
You can use a foreach over your array:
foreach (TextBox txt in txtTesting)
{
if (txt.text != "")
{
//
}
}
Or, the array has a length property that you can use.
for (int i = 1; i < txtTesting.length; i++)
{
if (txtTesting[i].text != "")
{
//
}
}
If you don't have an array of controls, you may want to look at this answer to loop through all the controls on your form. Except the generic Dictionary isn't in C# 2, so it will look more like this:
private void button1_Click(object sender, EventArgs e)
{
ArrayList txtTesting = ArrayList();
LoopControls(controls, this.Controls);
foreach (TextBox txt in txtTesting)
{
if (txt.text != "")
{
//
}
}
}
private void LoopControls(ArrayList list, Control.ControlCollection controls)
{
foreach (Control control in controls)
{
if (control is TextBox && control.Name.StartsWith("txtTesting"))
list.Add(control);
if (control.Controls.Count > 0)
LoopControls(list, control.Controls);
}
}

dynamically call a control

Let's say I have 30 controls, all lbls, all called "lblA" with a number after.
I also have 30 textboxes, same thing - called "txtB" with a number after.
How exactly would I formated this.
for (i = 1; i < this.controls.count;i++)
{
if ("lblA"+i=null)
{
break;
}
string A = string A + ("lblA" + i).Text
string B = string B + ("txtB" + i).Text
}
I've tried a few different things like calling the object with this.controls[i] but it's not exactly what I want. What I am doing is I have a lot of labels and text boxes in a form that are added at run time. I need to loop through the form to get them all. I'm writting it as a for each with quite a few ifs, but I'm curious if there's a dynamic way to do it.
I've looked for about 1-1:30 hours online and found nothing close to, thanks for the help all.
var labels = new Dictionary<int, string>();
for (i = 1; i < this.controls.count;i++)
{
var label = FindControl("lblA" + i) as Label;
if (label == null)
{
break;
}
labels.Add(i, label.Text);
}
What you want to use is the FindControl method.
Example in VB:
Dim txtMileage As TextBox = CType(cphLeft.FindControl("txtMileage" & iControlCountDays.ToString()), TextBox)
Maybe this will solve what you're after:
void GetSpecialControls() {
const string TXT_B = "txtB";
const string LBL_A = "lblA";
List<TextBox> textBoxList = new List<TextBox>();
List<Label> labelList = new List<Label>();
foreach (Control ctrl in this.Controls) {
Label lbl = ctrl as Label;
if (lbl != null) {
if (lbl.Text.IndexOf(LBL_A) == 0) {
labelList.Add(lbl);
}
} else {
TextBox txt = ctrl as TextBox;
if (txt != null) {
if (txt.Text.IndexOf(TXT_B) == 0) {
textBoxList.Add(txt);
}
}
}
}
Console.WriteLine("Found {0} TextBox Controls.", textBoxList.Count);
Console.WriteLine("Found {0} Label Controls.", labelList.Count);
}

Clear asp.net form at runtime

Whats the easiest way to clear an asp.net form at runtime using c#.
Thanks
Sp
I assume you want to clear input boxes, dropdowns etc. This can be done the following way in code to recursivly clear all data.
foreach( var control in this.Controls )
{
ClearControl( control );
}
and the recursive function
private void ClearControl( Control control )
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
// handle any other control //
foreach( Control childControl in control.Controls )
{
ClearControl( childControl );
}
}
I have used the following JS/c# to clear the form.
c# to add the js call onload
Page.ClientScript.RegisterStartupScript(typeof(WebForm3), "ClearPage", "ClearForm();", true);
the JS to clear the form
function ClearForm() {
var AllControls = document.getElementById('ctl00_ContentPlaceHolder1_PnlAll')
var Inputs = AllControls.getElementsByTagName('input');
for (var y = 0; y < Inputs.length; y++) {
// define element type
type = Inputs[y].type
// alert before erasing form element
//alert('form='+x+' element='+y+' type='+type);
// switch on element type
switch (type) {
case "text":
case "textarea":
case "password":
//case "hidden":
Inputs[y].value = "";
break;
}
}
}

Categories