Reputation: 13
How can I add values in my dynamically created texbox in another textbox ? For example I have 6 textbox named from TextBox0 to TextBox6 and I want to add the values in TextBox0 to TextBox5 then set that values in TextBox6. How can I do that?
This is my code for create dynamic textbox:
static int column = 0;
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
if (column > 0)
{
do
{
TextBox tb = new TextBox();
tb.Text = "";
tb.Name = "TextBox" + (i + column * 6);
TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
Point p = new Point(15 + (column * 125), 5 + (i * 25));
tb.Location = p;
this.Controls.Add(tb);
i++;
} while (i <= 5);
}
else
{
do
{
TextBox tb = new TextBox();
tb.Text = "";
tb.Name = "TextBox" + i;
TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
Point p = new Point(15, 5 + (i * 25));
tb.Location = p;
this.Controls.Add(tb);
i++;
} while (i <= 5);
}
column++;
}
Upvotes: 1
Views: 112
Reputation: 3422
private const string _textBoxName = "TextBox";
The method count textboxes sum by given range of text box ids. Be aware this will throw exception if the text box texts / name id are not intgeres or
private int Count(int from, int to)
{
int GetIdFromTextBox(TextBox textBox) => int.Parse(new string(textBox.Name.Skip(_textBoxName.Length).ToArray()));
var textBoxes = Controls.OfType<TextBox>().ToList();
var textBoxesWithIds = textBoxes.Select(textBox => (textBox: textBox, id: GetIdFromTextBox(textBox))).ToList();
var sum = textBoxesWithIds.Where(x => x.id >= from && x.id <= to).Sum(x => int.Parse(x.textBox.Text));
return sum;
}
Upvotes: 1