How to insert text into Textboxes dynamically? - c#

I am working on a Project in C#, i need to insert text into textfields which are more then 250,
i stored the data in an array of string , now i have to insert data from array into these 250 textboxes in sequence like
textbox1.Text=StringArray[1];
textbox2.Text=StringArray[2];
. .
. .
. .
textbox250.Text=StringArray[250];
i google it no positive results ,
i did code to clear text from all the textboxes, i.e
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
i tried to insert text like this
Action<Control.ControlCollection> func = null;
int i=0;
func = (controls) =>
{
foreach (Control control in controls)
{
if (control is TextBox)
(control as TextBox).Text = result_set[i++].ToString();
else
func(control.Controls);
}
};
func(Controls);
but got an exception of type 'System.IndexOutOfRangeException'.

The error is because you access a member outside of the array. It could be because you have other textboxes on the page which are found by the loop and then your array index runs out of range. Maybe you could do something like this:
for(int i = 1; i <= StringArray.Length; i++)
{
// I don't know which technology you use, it might be a different method to find
Control control = controlCollection.FindByName("Textbox" + i.ToString();
if (control is TextBox)
(control as TextBox).Text = StringArray[i];
}

You can add an attribute "index" to every textbox on your page with the index of the array, and attach a function to the event "OnInit" in order to insert the text. An example:
PAGE:
[asp:TextBox ID="TextBox1" runat="server" OnInit="setText" index="1"][/asp:TextBox]
[asp:TextBox ID="TextBox2" runat="server" OnInit="setText" index="2"][/asp:TextBox]
...
CODE BEHIND:
public void setText(object sender, System.EventArgs e) {
TextBox tbx;
tbx = sender;
tbx.Text = StringArray[sender.attributes["index"]];
}
Hope this helps!

Related

Getting IDs and values of dynamically created text boxes on Page_Load

I have a web application asp.net.
I am creating 54 text boxes dynamically in Page_Load
Here is the code
protected void Page_Load(object sender, EventArgs e)
{
for(i = 0, i<54, i++)
{
Textbox TestTextbox = new texbox();
TestTextBox.ID = "Reg" + i ;
TestTextBox.Attributes.add("runat","server");
TestTextBoxAttributes.Add("AutoPostBack", "true");
//display to a table called table1 created in the aspx page
}
}
On the page I have a button, called button1, and a on click event called "OnClickEvent", i want to capture the ID and the values of all the textboxes.
I have used Page.Controls.Count and I get only 1, the table that I have added to the aspx page, I get the IDs by using Request.Form but I`m not getting the values.
I am adding all the text boxes to a Table that I have created in the aspx file.
You can loop through the controls and check if they are of type TextBox:
for(int i = 0, i<54, i++)) {
var control = Page.FindControl("Reg" + i);
//get the value of the control
}
You are not adding the TextBox to the Page, so you cannot find it anyway. Second, adding runat=server and AutoPostBack=true as a string would not work either. (not to mention your snippet is full of errors)
//a loop uses ';', not ','
for (int i = 0; i < 54; i++)
{
//declare a new dynamic textbox = CaSe SeNsItIvE
TextBox TestTextbox = new TextBox();
TestTextbox.ID = "Reg" + i;
//if you want to add attibutes you do it like this
TestTextbox.AutoPostBack = true;
TestTextbox.TextChanged += TestTextbox_TextChanged;
//add the textbox to the page
PlaceHolder1.Controls.Add(TestTextbox);
}
And if you want to loop all the controls you can do something like this
//loop all the controls that were added to the placeholder
foreach (Control control in PlaceHolder1.Controls)
{
//is it a textbox
if (control is TextBox)
{
//cast the control back to a textbox to access it's properties
TextBox tb = control as TextBox;
string id = tb.ID;
}
}

How can I shorten this repetitive C# TextBox.Clear code?

Been reading through the threads a lot recently as I am learning to code!
In essence all I know is self taught and very basic, so I would like to start becoming more professional
I would like to shorten this code down (in the simplest way possible) since I often end up with very repetitive code! Here is a primary example
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox10.Clear();
textBox11.Clear();
textBox12.Clear();
}
For context I can't clear all textboxes on my form since textBox13 always has a useful value that I can't have deleted!
EDIT * textBoxes 1 to 6 are in groupBox1, and textBoxes 7-12 are in groupBox2. This appears to be significant; I was just using the groupbox tool to make the program clear!
If anyone can help I would be truly grateful! Please keep in mind I am still a coding novice, so some features I am unfamiliar with.
Here is an image of the program to help!
Assuming all your textboxes name start in the format you displayed, you could use this:
foreach (Control control in Controls)
{
if (control.Name.StartsWith("textBox") && !control.Name.EndsWith("13") && control.GetType() == typeof(TextBox))
{
TextBox textBox = (TextBox)control;
textBox.Clear();
}
}
EDIT
If you want it to work with group boxes use this code by calling ClearTextBoxes (just write "ClearTextBoxes();")
private void ClearTextBoxes()
{
foreach (Control control in Controls)
{
ClearTextBox(control);
}
}
private void ClearTextBox(Control control)
{
if (control.GetType() == typeof(TextBox))
{
if (control.Name.StartsWith("textBox") && !control.Name.EndsWith("13"))
{
TextBox textBox = (TextBox)control;
textBox.Clear();
}
}
else if (control.GetType() == typeof(GroupBox))
{
GroupBox groupBox = (GroupBox)control;
foreach (Control groupBoxControl in groupBox.Controls)
{
ClearTextBox(groupBoxControl);
}
}
}
The current setting doesn not allow you to clear everything quickly because each variable, even if they're all of the same type and with similar name, is a different entity and you cannot iterate through them.
Anyway, you could group them in an array and iterate through them like this:
// Fill this array in an Init function
YourType[] textBoxes;
private void button2_Click(object sender, EventArgs e)
{
// Iterate through the whole array except for the last element
for(int i=0; i<textBoxes.Length-1; i++)
{
textBoxes[i].Clear();
}
}
One possible solution would be store textboxes in list
List<TextBox> textBoxes
And then iterate through this collection using for or foreach loop and calling Clear() method.
Or use extension method ForEach()
textBoxes.ForEach(x => x.Clear());
The simplest way is to prepare a collection containing all of your textbox objects
var textBoxes = new List<TextBox> { textBox1,textBox2,textBox3};// fill in the rest
and just iterate with a 'foreach' on it
textBoxes.ForEach(textBox => textBox.Clear());
This is a simple suggestion.
You can also use reflection to make it more implicit but it doesn't worth it
Usually having too many of certain control can be a sign that you can consider a different type of control, but that doesn't seem to be the case based on the screenshot. You can use array:
foreach (var t in new[] { textBox1, textBox2, textBox3 })
t.Clear();
If the controls are directly in the form then something like:
foreach (Control c in this.Controls)
if (c is TextBox && c.Name != "textBox13")
c.Text = ""; // .Text = "" is what TextBox.Clear() does
but because the controls are inside other controls:
foreach (Control c in this.groupBox1.Controls) if (c is TextBox) c.Text = "";
foreach (Control c in this.groupBox2.Controls) if (c is TextBox) c.Text = "";
or:
foreach (var gb in new[] { groupBox1, groupBox2 })
foreach (Control c in gb.Controls)
if (c is TextBox) c.Text = "";

How to loop through all controls in All ASP.NET UpdatePanels in the page?

I am using the following code to loop through my controls. The problem is that I have put all of these controls including TextBox and DropDownList inside AJAX UpdatePanel control and those panels never get reached. I have around three UpdatePanels in the page, so how can I loop through all the controls TextBox and DropDownList inside each UpdatePanel?
This code only works for one UpdatePanel:
foreach (Control c in UpdatePanel2.Controls)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = string.Empty;
}
}
}
It should work:
foreach (Control c in Page.Controls)
{
if (c is UpdatePanel)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).Text = string.Empty;
}
}
}
}
To scroll controls within the UpdatePanel do something like this:
For Each ctrl As Control In UpdatePanel1.ContentTemplateContainer.Controls
If ctrl.GetType() Is GetType(TextBox) Then
End If
Next
Itiel's answer did not work in my scenario. I have 6 gridviews in an updatepanel. Since it was only one type of control I was looking for inside the UpdatePanel the below routine worked like a charm! My goal was to enable or disable all gridviews on the page with one button click that calls ChangeControlStatus(true or false) method. Maybe it will help someone.
private void ChangeControlStatus(bool status)
{
int i = 1;
//loop through 6 gridviews
for (i = 1; i <= 6; i++)
{
//enable/disable all grids on the page
GridView gv = UpdatePanel1.FindControl("UpdatePanel1").FindControl("Gridview" + i) as GridView;
gv.Enabled = status;
} }

Windows form Create 10 textBox dynamic this text value how to access?

Dynamic 10 textbox create all text value how to access in button click event in windows form application
The most simple way to do this is create a list to keep textbox's references.
List<TextBox> textBoxList = new List<TextBox>();
for (int index = 0; index < 10; index++)
{
var textBox = new TextBox();
textBoxList.Add(textBox);
// do the rest of work.
}
You can get its reference inside click event handler like below.
// inside button's click event.
foreach (var textBox in textBoxList)
{
// get text and do the work.
}
The simplest way assign something to the tag property that help you to identify the textbox. For example a number or an enum value.
Then casting the click event sender to a text box and look in the tag which one is it.
TextBox txt = new TextBox();
txt.Text = "ABC";
this.Controls.Add(txt);
private void btnOk_Click(object sender, EventArgs e)
{
foreach (Control ctl in this.Controls)
{
if (ctl.GetType() == typeof(TextBox))
MessageBox.Show(ctl.Text);
}
}
You can create an array of 10 text boxes dynamically place all the text boxes
You can access the text value based on the array values (0-9) of it

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
}
}

Categories