I want to add controls to my aspx web form at runtime using C#.
I would like to write a generic function which will create any type of control (Eg: textbox, lable, button etc).
Any ideas please.
Thanks
BB
You can do this, as long as the control types you want to use all have a default constructor.
T AddControl<T>() where T : WebControl, new()
{
T ctrl = new T();
...
return ctrl;
}
I suppose you could do something like this:
public void CreateControl<W>(Func<W> controlConstructor) where W : WebControl
{
W control = controlConstructor();
//add control and configure it, etc etc
}
Add TextBoxes Control to Placeholder
private void CreateTextBoxes()
{
for (int counter = 0; counter <= NumberOfControls; counter++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + (counter + 1).ToString();
// add some dummy data to textboxes
tb.Text = "Enter Title " + counter;
phTextBoxes.Controls.Add(tb);
phTextBoxes.Controls.Add(new LiteralControl("<br/>"));
}
}
In CreateTextBoxes method I loop through ‘n’ numbers of controls that we wants to create dynamically in phTextBoxes placeholder.
Related
I have a form (Windows Forms) with dynamically created textboxes:
TextBox[] tbxCantServ = new TextBox[1];
int i;
for (i = 0; i < tbxCantServ.Length; i++)
{
tbxCantServ[i] = new TextBox();
}
foreach (TextBox tbxActualCant in tbxCantServ)
{
tbxActualCant.Location = new Point(iHorizontal, iVertical);
tbxActualCant.Name = "tbx" + counter++;
tbxActualCant.Visible = true;
tbxActualCant.Width = 44;
tbxActualCant.MaxLength = 4;
this.Controls.Add(tbxActualCant);
}
Now I want to fill them with data, how could I do that?
If I created some textboxes dynamically with the names:
"tbxActualServ.Name = "txt" + counter;"
How can I write in them? How can I access to them?
For example, if I have created tbx1, tbx2 and tbx3, I would have a "for" that fills tbx1.Text with "1", tbx2.Text with "2", and tbx3.Text with "3".
something like
"for from i=0 to counter {
tbx[i] = i
}"
of like:
this.Controls.OfType<TextBox>().Where(r => r.Name == "tbx" + counter).¿¿Write??(r => r.Text = i).ToString();
Thanks!
You could do something like this:
this.Controls.OfType<TextBox>().ToList<TextBox>().ForEach(tb => tb.Text = "bla bla");
Evening,
Guessing from your tags that this is a web forms project.. Im going to have to make some other assumptions.
I am guessing that you are creating your text boxes in code, something like
TextBox tb1 = new TextBox();
form1.Controls.Add(tb1);
TextBox tb2 = new TextBox();
form1.Controls.Add(tb2);
If this is the case then I believe that you could do something like this:
for (int i = 0; i < 2; i++)
{
TextBox tb1 = page.findControl("tb" + i.ToString());
tb1.Text = "This is number " + i.ToString();
}
There is another alternative, you could keep a collection of the controls as you create them, you could then iterate over the collection.
To be honest, without more details about your code it will be difficult to give a full answer, I think that this answers what you are looking for, if not update your question with more details and more of the code (the code where you are dynamically creating the controls would be useful)
While it's possible to access controls by their names (the way you do it depends on the technology - are you using WinForms, WPF, Web Forms, ...?), using an array of controls is a much better solution. Here's some pseudo-C#:
MyControl[] controls = new MyControl[length];
for(int n = 0; n < controls.Length; n++)
{
controls[n] = new MyControl(...);
}
// ...
for(int n = 0; n < controls.Length; n++)
{
DoSomethingWith( controls[n] );
}
I'm trying to make a small app, for make my job easier creating definitions (new web forms aspx) via WinForms C#.
Now I have this form, where I tell the app how many textboxes I want to create.
After their creation, I want to assign to a string the textboxes values that I wrote.
private void CreateControls()
{
for (int index = 0; index < NumberOfRows; index++)
{
TextBox textBox = new TextBox();
textBox.Name = "TextBox" + (index + 1).ToString();
textBox.Size = new Size(120, 20);
textBox.Location = new Point(X, Y + 26);
ComboBox comboBox = new ComboBox();
comboBox.Name = "ComboBox" + (index + 1).ToString();
comboBox.Size = new Size(75, 20);
comboBox.Location = new Point(141, Y + 26);
comboBox.DataSource = Enum.GetNames(typeof(DataTypes));
Y += 26;
this.Controls.Add(textBox);
this.Controls.Add(comboBox);
}
}
Now, I don't know how to check if the textboxes are created, and then take their values.
Could anyone refer me something? Thanks :)!
You'll need to, on Page_Load, find those controls and grab their values. Since you gave them meaningful names when you created them, this should do the trick:
for (int index = 0; index < NumberOfRows; index++)
{
TextBox textBox = this.FindControl(
string.Format("TextBox{0}", index)) as TextBox;
if (textBox == null) { continue; } // this means it wasn't found
var text = textBox.Text;
// work with the text
}
However, if the ComboBox class you're using isn't a third-party one and it's not an ASP.NET application, the code would work for a Windows Forms application as well with a minor modification:
for (int index = 0; index < NumberOfRows; index++)
{
// you have to use the Find method of the ControlCollection
TextBox textBox = this.Controls.Find(
string.Format("TextBox{0}", index)) as TextBox;
if (textBox == null) { continue; } // this means it wasn't found
var text = textBox.Text;
// work with the text
}
I tend to agree with the community that it's probably a Windows Forms application because you can't set the Location of a standard ASP.NET control. However, if these are user controls, or third-party ones, that support those properties and render the appropriate CSS then we'd never know.
if(Page.FindControl("IDofControl") != null)
//exists
else
//does no exists
Suppose I have this in page load:
Label lblc = new Label();
for (int i = 1; i <= 10; i++)
{
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
How can I manipulate each of these controls at run time?
I want to:
Set/get their text.
Reference a particular control, in this case Label.
Use an array if you know how many labels you will have,
Label[] lblc = new Label[10];
for (int i = 0; i < 10; i++)
{
lblc[i] = new Label() { Text = (i + 1).ToString() };
this.Controls.Add(lblc[i]);
}
Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.
List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
lblc.Add(new Label() { Text = (i + 1).ToString() });
this.Controls.Add(lblc[i]);
}
You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.
Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox
List<Control> controlList = new List<Control>();
for (int i = 0; i < 10; i++)
{
control.Add(new Label() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
control.Add(new TextBox() { Text = control.Count.ToString() });
this.Controls.Add(control[control.Count - 1]);
}
Good luck! Anything else that needs to be added just ask.
Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Text = i.ToString();
lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
.....
.....
}
Better to set the Name and then use that to distinguese between the controls
for (int i = 1; i <= 10; i++)
{
Label lblc = new Label();
lblc.Name = "lbl_"+i.ToString();
lblc.Text = i.ToString();
this.Controls.Add(lblc);
}
when:
public void SetTextOnControlName(string name, string newText)
{
var ctrl = Controls.First(c => c.Name == name);
ctrl.Text = newTExt;
}
Usage:
SetTextOnControlName("lbl_2", "yeah :D new text is awsome");
I can't manage to get the values from textboxes that are created at run-time.
I want an user to choose something from a checkedlistbox, and to enter any values he wants in textboxes that are created at every button click.
How can I get the name of those texboxes? They really exist? I am a beginner and I really don't understand how they are created.
This is my code where I create textboxes.
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 466;
int y = 84;
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
int i = 0;
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
tb.Name = "txtBox" + i++.ToString();
Controls.Add(tb);
y += 30;
}
just place the i outside the foreach and done.
int i = 0;
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
i++;
string textBoxName = "textBox" + i.ToString();
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
//tb.Name = "txtBox" + i++.ToString(); <--Your Version
tb.Name = textBoxName;
//...
//Other stuff or your codes
}
Rather than searching for exact name what you can do is have a string(fixed) which is searched for the control.
so if you find that string ( in your case which is 'textbox' ), what you can do is search for that fixed string in the name of control. if it exists then it's dynamically generated control.
foreach(Control c in parentControlIdOrName.Controls)
{
if(c.GetType()==typeof(TextBox))
{
if(((TextBox)c).Name.indexOf("textbox")!=-1)
{
// do your coding here...what ever you want....
}
}
}
Haven't tested but,Hope for the best. It might work.
I want to create 16 Textboxes, named textbox1 to textbox16, inside a for loop which runs for 16 times. Hence, 1 textbox is created in each loop. How to achieve this ?
You can't make dynamically named variables. In this kind of situationen, it makes most sense to keep the controls in some collection, for instance in a List<T>:
List<TextBox> textBoxes = new List<TextBox>();
for(int i = 1 ; i <= 16 ; i++ )
{
var tb = new TextBox() { Name = "textbox" + i };
textBoxes.Add(tb);
}
Try this :
for(int counter=0;counter<16;counter++){
TextBox TB = new TextBox();
TB.Id = "textbox" + (counter + 1);
// code to add this textbox in screen
}