Dynamic naming of variable inside for loop - c#

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
}

Related

Change text in multiple textboxes?

How would I go about making a for loop that changes the text in more than 1 textbox?
for (int i; i < 5; i++)
{
textbox(i).text = "something"
}
But I don't know how to get the I to represent the number after the textbox, does anyone know how to?
Store the textboxes in an Array and then loop over the array
for (int i; i < 5; i++)
{
textboxArray[i].text = "something"
}
You could use Controls.Find:
var txts = this.Controls.Find("textbox" + i, true); // true for recursive search
foreach(TextBox txt in txts)
txt.Text = "something";
or - if the TextBoxes are in the same container control(like the Form or a Panel)- with LINQ:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name == "textbox" + i);
foreach(TextBox txt in txts)
txt.Text = "something";
Actually you don't need the loop variable, you could also use String.StartsWith to get all:
var txts = this.Controls.OfType<TextBox>().Where(txt => txt.Name.StartsWith("textbox"));
foreach(TextBox txt in txts)
txt.Text = "something";
if you dont want to alter every textbox on your form just simply add them to a List:
List<TextBox> TextBoxes = new List<TextBox>();
TextBoxes.Add(This.TextBox1);
TextBoxes.Add(This.TextBox3):
then as others have suggested you could either linq or regular foreach the textboxes in the list
TextBoxes.Foreach(Textbox => TextBox.Text = "something");
or
foreach (TextBox r in TextBoxes)
{
r.Text = "something;
}

How to write to a dynamical number of Textboxes?

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] );
}

Check if TextBox is created, then assign it's value

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

Generic function to create controls at runtime

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.

WinForms: variable number of dynamic TextBox controls

I have to create variable number of Labels and next to them TextBox controls - arranging the whole thing into a column, each line a Label and a TextBox. If the my Main window is smaller than the total height of all the TextBox controls, somehow I need a scrollbar which can scroll the list of TextBoxes. Pressing the enter key would have to take the focus to the next TextBox and also scroll in case of too many TextBoxes.
This is a rather generic problem, I guess there are already some pre-baked solutions for this.
Any advice?
Use a TableLayoutPanel. You can dynamically add controls, specify their row/column, and it will maintain a scrollbar for you (with the appropriate settings). It has its quirks, but should suit for this case.
If you use the WinForms designer to place the TableLayoutPanel, then you can use it to also define the style of the columns. You can also vary the style of each row as suggested by Tcks.
To add the control with a specified row/column:
int column = 42;
int row = 7;
myTableLayoutPanel.Controls.Add(new TextBox(), column, row);
You can use TableLayoutPanel as container for controls (Labels and TextBoxes) and create them dynamicaly in code.
Example:
void Form1_Load( object sender, EventArgs e ) {
const int COUNT = 10;
TableLayoutPanel pnlContent = new TableLayoutPanel();
pnlContent.Dock = DockStyle.Fill;
pnlContent.AutoScroll = true;
pnlContent.AutoScrollMargin = new Size( 1, 1 );
pnlContent.AutoScrollMinSize = new Size( 1, 1 );
pnlContent.RowCount = COUNT;
pnlContent.ColumnCount = 3;
for ( int i = 0; i < pnlContent.ColumnCount; i++ ) {
pnlContent.ColumnStyles.Add( new ColumnStyle() );
}
pnlContent.ColumnStyles[0].Width = 100;
pnlContent.ColumnStyles[1].Width = 5;
pnlContent.ColumnStyles[2].SizeType = SizeType.Percent;
pnlContent.ColumnStyles[2].Width = 100;
this.Controls.Add( pnlContent );
for ( int i = 0; i < COUNT; i++ ) {
pnlContent.RowStyles.Add( new RowStyle( SizeType.Absolute, 20 ) );
Label lblTitle = new Label();
lblTitle.Text = string.Format( "Row {0}:", i + 1 );
lblTitle.TabIndex = (i * 2);
lblTitle.Margin = new Padding( 0 );
lblTitle.Dock = DockStyle.Fill;
pnlContent.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
txtValue.TabIndex = (i * 2) + 1;
txtValue.Margin = new Padding( 0 );
txtValue.Dock = DockStyle.Fill;
txtValue.KeyDown += new KeyEventHandler( txtValue_KeyDown );
pnlContent.Controls.Add( txtValue, 2, i );
}
}
void txtValue_KeyDown( object sender, KeyEventArgs e ) {
if ( e.KeyCode == Keys.Enter ) {
SendKeys.Send( "{TAB}" );
}
}
Also, check the generated code of a window/usercontrol after adding some controls to it. It should give you a good idea of how this could be done dynamically. (I'm talking about the somename.cs.designer file)

Categories

Resources