dynamically create multiple textboxes C# - c#

This is my code.
But all my textboxes's value is just null.
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[teams];
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
i++;
}
}
Thanks for the help.

The array creation call just initializes the elements to null. You need to individually create them.
TextBox[] txtTeamNames = new TextBox[teams];
for (int i = 0; i < txtTeamNames.Length; i++) {
var txt = new TextBox();
txtTeamNames[i] = txt;
txt.Name = name;
txt.Text = name;
txt.Location = new Point(172, 32 + (i * 28));
txt.Visible = true;
}
Note: As several people have pointed out in order for this code to be meaningful you will need to add each TextBox to a parent Control. eg this.Controls.Add(txt).

You need to initialize your textbox at the start of the loop.
You also need to use a for loop instead of a foreach.

You need to new up your TextBoxes:
for (int i = 0; i < teams; i++)
{
txtTeamNames[i] = new TextBox();
...
}

You are doing it wrong, you have to add textbox instances to the array, and then add it to the form. This is how you should do it.
public void createTxtTeamNames()
{
TextBox[] txtTeamNames = new TextBox[10];
for (int u = 0; u < txtTeamNames.Count(); u++)
{
txtTeamNames[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}

private void button2_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = abc;
tb.Text = "" + i;
Point p = new Point(20 + i, 30 * i);
tb.Location = p;
this.Controls.Add(tb);
i++;
}
private void button3_Click(object sender, EventArgs e)
{
foreach (TextBox item in this.Controls.OfType<TextBox>())
{
MessageBox.Show(item.Name + ": " + item.Text + "\\n");
}
}

Related

Creating variables from dynamically created Text boxes and labels using C#

I am wanting to use to names assigned using .Name to input from text boxes then calculate and output to the labels.
Not sure how I can refer to these inputs as they currently have names but no assigned variables.
Sorry if I don't make much sense I am not a very proficient coder.
public partial class Form1 : Form
{
List<TextBox> Txt1 = new List<TextBox>();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 7; j++)
{
if (j == 0)
{
var txtbox = new TextBox();
txtbox.Location = new Point(163 + (i * 220), (36));
txtbox.Name = i + "Names";
txtbox.Text = txtbox.Name;
txtbox.Width = 40;
this.Controls.Add(txtbox);
}
else if (j>0 && j<6)
{
var extratxt = new TextBox();
extratxt.Location = new Point(163 + (i * 220), (36+ 36 * j));
extratxt.Name = i + "Input" + j;
extratxt.Text = extratxt.Name;
extratxt.Width = 70;
this.Controls.Add(extratxt);
var percentbox = new Label();
percentbox.Location = new Point(163 + (90+ i * 220), (36 + 36 * j));
percentbox.Name = i + "Percent" + j;
percentbox.Text = percentbox.Name;
percentbox.Width = 50;
this.Controls.Add(percentbox);
var gradebox = new Label();
gradebox.Location = new Point(163 + (150 + i * 220), (36 + 36 * j));
gradebox.Name = i + "Grade" + j;
gradebox.Text = gradebox.Name;
gradebox.Width = 50;
this.Controls.Add(gradebox);
}
else
{
var totals = new Label();
totals.Location = new Point(163 + (i * 220), (36 + 36 * j));
totals.Name = i + "Total";
totals.Text = totals.Name;
totals.Width = 40;
this.Controls.Add(totals);
...
}
...
}
}
}
}
Hope I understand you correctly.
Basically, your difficulty is how to access the instance stored in list of the dynamically create controls by their name, right?
Well, you can use .FirstOrDefault() to select instance with a specific property. For example,
private void Form1_Load(object sender, EventArgs e)
{
List<TextBox> tbList = new List<TextBox>();
for (int i = 0; i < 3; i++)
{
TextBox tb = new TextBox();
tb.Text = "Test" + i.ToString();
tb.Name = "TextBox" + (i + 1).ToString();
tb.Location = new Point(0, 25 * i);
tb.Tag = i;
tbList.Add(tb);
this.Controls.Add(tb);
}
var tb2 = tbList.FirstOrDefault(tb => tb.Name == "TextBox2");
if (tb2 != null)
tb2.Text = "Modified text";
var sum = tbList.Sum(tb => (int)tb.Tag);
}

Foreach sum of textboxes c#

I got 2 panels with textboxes and labels.I am trying to make the sum of panel1.texbox1*panel2.textbox1 + panel1.textbox2... and so on.But when I am running the program it actually shows me the product of all the textboxes.
Here I have the code for creating textboxes and labels:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int j,c=1;
int i = comboBox1.SelectedIndex;
if (i != null)
{
for (j = 0; j <= i; j++)
{
Label label = new Label();
label.Text = "w" + c;
label.Location = new System.Drawing.Point(5, 20 + (20 * c));
label.Size = new System.Drawing.Size(30, 20);
panel1.Controls.Add(label);
Label label2 = new Label();
label2.Text = "x" + c;
label2.Location = new System.Drawing.Point(5, 20 + (20 * c));
label2.Size = new System.Drawing.Size(30, 20);
panel3.Controls.Add(label2);
TextBox w = new TextBox();
w.Text = "";
w.Location = new System.Drawing.Point(35, 20 + (20 * c));
w.Size = new System.Drawing.Size(25, 20);
panel1.Controls.Add(w);
TextBox x = new TextBox();
x.Text = "";
x.Location = new System.Drawing.Point(35, 20 + (20 * c));
x.Size = new System.Drawing.Size(25, 20);
panel3.Controls.Add(x);
c++;
}
}
}
And here is the code that I tried to use:
private void button4_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (Control w1 in panel1.Controls.OfType<TextBox>())
{
foreach (Control w2 in panel3.Controls.OfType<TextBox>())
{
int textB1 = int.Parse(w1.Text);
int textB2 = int.Parse(w2.Text);
int textB3 = textB1 * textB2;
}
}
textBox3.Text = "" + suma;
}
You can do it in one line with linq, but you'll of course have to check for valid input in the text boxes first:
var panel1Texts = panel1.Controls.OfType<TextBox>().ToArray();
var panel2Texts = panel2.Controls.OfType<TextBox>().ToArray();
Func<TextBox, bool> isInvalid = (text) =>
{
int res;
return !int.TryParse(text.Text, out res);
};
var errorText = panel1Texts.FirstOrDefault(isInvalid);
if (errorText != null)
{
// Error handling
}
errorText = panel2Texts.FirstOrDefault(isInvalid);
if (errorText != null)
{
// Error handling
}
var sum = panel1Texts.Zip(panel2Texts, (tb1, tb2) => int.Parse(tb1.Text) * int.Parse(tb2.Text)).Sum();
textBox3.Text = sum.ToString();
In your current code you are casting all your controls including your labels to textbox by doing OfType<TextBox>() on them as the collection also included labels.
Here is what i think you should do :
TextBox3.Text = (Panel1.Controls.OfType<Control>().Where(c => c.GetType() == typeof(TextBox)).Sum(v => int.Parse(v.Text)) + Panel2.Controls.OfType<Control>().Where(x => x.GetType() == typeof(TextBox)).Sum(z => int.Parse(z.Text))).ToString();

how to dynamically create textboxes by defined variable?

I am trying to do something like this : I have a textbox in which I put a number.
When I press enter I save this number in my variable id.
Then I want to create the exact same number of textboxes as my id variable.
It doesn't work because you can't set unknown variable in an array but how could I modify this code to get the result I want?
private void tbNbCat_KeyDown(object sender, KeyEventArgs e)
{
int id=0;
if (e.KeyCode == Keys.Return){
id = int.Parse(tbNbCat.Text);
MessageBox.Show(id.ToString());
createTxtTeamNames(id);
}
}
public void createTxtTeamNames(int id)
{
TextBox[] txtTeamNames = new TextBox[id];
for (int u = 0; u < id; u++)
{
txtTeamNames[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in txtTeamNames)
{
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
Thanks.
Change
TextBox[] txtTeamNames = new TextBox[id];
To
List<TextBox> txtTeamNames = new List<TextBox>();
Why are you using the array in the first place?
public void createTxtTeamNames(int id)
{
for (int i = 0; i < id; ++i)
{
TextBox txt = new TextBox();
string name = "TeamNumber" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(0, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
}
}

Retrieve value from dynamic TextBox

I have a Button that creates a list of TextBoxes Dynamically and I also have a Button that submits the information. However I don't know how to access the values of the Textboxes. Below is the code:
if (IsPostBack)
{
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + 1;
int Count = int.Parse(string.Format("{0}", ViewState["count"]));
var lstTextBox = new List<TextBox>();
for (int i = 0; i < Counter; i++)
{
TextBox txtbx = new TextBox();
txtbx.ID = string.Format("txtbx{0}", i);
// txtbx.AutoPostBack = true;
lstTextBox.Add(txtbx);
//txtbx.Text = "initial value";
}
Session["lstTextBox"] = lstTextBox;
}
protected void Button1_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)//Calls to createbox
CreateTextBox(i);
//Label1.Text = Counter.ToString();
if (Counter == 4)
{
Button1.Visible = false;
}
}
private int Counter
{
get { return Convert.ToInt32(ViewState["count"] ?? "0"); } //Fields button counter
set { ViewState["count"] = value; }
}
private void CreateTextBox(int j) //Creates the fields / cells
{
var box = new TextBox();
box.ID = "Textbox" + j;
box.Text = "Textbox" + j;
var c = new TableCell();
c.Controls.Add(box);
r.Cells.Add(c);
table1.Rows.Add(r);
}
How would like to have Button2 grab the values.
Thank you in advance!!
do it like this
foreach(Control c in YourControlHolder.Controls)
{
if(c is TextBox)
{
//your code here.
}
}

How to get the values dynamically added controls in other parts of the code?

I have a method that creates textboxes depending on the number of parameters values that the user has to enter.And its working fine. The problem is that when the user clicks Ok i want to take the value that the user entered in these textboxes and replace them in a string. When am searching these textboxes to get the text value from them am not finding them. How do i get these values to continue my project? the code is:
protected void btnPreview_Click(object sender, EventArgs e)
{
lbHeader.Text = "Template Designer";
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = false;
divFloating.Visible = true;
if (txtQuery.Text.Contains("WHERE") || txtQuery.Text.Contains("where")||txtQuery.Text.Contains("Where"))
{
string[] splitter=new string[10];
splitter[0]="Where";
splitter[1]="WHERE";
splitter[2]="where";
splitter[3]="AND";
splitter[4] = "and";
splitter[5] = "And";
string[] condition=txtQuery.Text.Split(splitter, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] Condition1 =null;
Label[] newLabel = new Label[10];
TextBox[] txtBox = new TextBox[10];
for (int i = 0; i < numberOfParameters; i++)
{
string lbValue="lbValue";
string lbID=lbValue+i;
string txtValue = "txtValue";
string txtID = txtValue + i;
HtmlGenericControl genericControl = new HtmlGenericControl("br/");
Condition1 = condition[i + 1].Split('[', ']');
newLabel[i] = new Label();
txtBox[i] = new TextBox();
newLabel[i].ID=lbID;
newLabel[i].Text = Condition1[1];
txtBox[i].ID = txtID;
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
txtBox[i].EnableViewState = true;
}
}
}
private bool ControlExistence(string lbID)
{
try
{
td2.FindControl(lbID);
return true;
}
catch(Exception ex)
{
return false;
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
// GetTextBoxValues();
string[] splitter1 = new string[10];
splitter1[0] = "Where";
splitter1[1] = "WHERE";
splitter1[2] = "where";
splitter1[3] = "AND";
splitter1[4] = "and";
splitter1[5] = "And";
string[] condition = txtQuery.Text.Split(splitter1, StringSplitOptions.None);
int numberOfParameters = condition.Length - 1;
string[] splitter = new string[4];
splitter[0] = "[";
splitter[1] = "]";
splitter[2] = "'";
string[] queryBoxValue = txtQuery.Text.Split(splitter,StringSplitOptions.RemoveEmptyEntries);
StringBuilder query = new StringBuilder();
TextBox txtBox = new TextBox();
for (int i = 0; i < queryBoxValue.Length; i++)
{
if (!queryBoxValue[i].Contains("?"))
{
query.Append(queryBoxValue[i]);
query.Append(" ");
}
else
{
for (int counter1 = 0; counter1 < numberOfParameters; counter1++)
{
string txtValue = "txtValue";
string txtID = txtValue + counter1;
if (ControlExistence(txtID))
{
TextBox box = (TextBox)td2.FindControl(txtID);
string b = box.Text;
//txtBox.ID = txtID;
}
txtBox.Text = "'" + txtBox.Text + "'";
queryBoxValue[i] = queryBoxValue[i].Replace(queryBoxValue[i], txtBox.Text);
query.Append(queryBoxValue[i]);
}
}
}
string fireQuery = query.ToString();
adp = new SqlDataAdapter(fireQuery, conn);
tab = new DataTable();
adp.Fill(tab);
if (tab.Rows.Count > 0)
{
string[] tempString = txtTemplate.Text.Split(' ');
for (int j = 0; j < tempString.Length; j++)
{
if (tempString[j].StartsWith("["))
{
txtPreview.Text = txtTemplate.Text.Replace(tempString[j], tab.Rows[0][0].ToString());
}
}
}
divFloating.Visible = false;
divQueryBuilder.Visible = false;
divTemplateDesigner.Visible = true;
}
Please help. This has become a blocker for me.
Have a list of the added controls and use it when needed.
for (int i = 0; i < numberOfParameters; i++)
{
// ...
td2.Controls.Add(newLabel[i]);
td2.Controls.Add(genericControl);
td2.Controls.Add(txtBox[i]);
td2.Controls.Add(genericControl);
addedTextBoxes.Add(txtBox[i]);
// ...
}
And then from another part of your code:
var values = addedTextBoxes.Select(tb => tb.Text).ToList();
foreach (var txtBox in addedTextBoxes)
{
// ...
}
etc...

Categories