Foreach sum of textboxes c# - 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();

Related

Unable to grab values from text boxes on form

So i am trying to grab user input from my text boxes which are being printed to the screen through a loop and if Statements. When trying to print the values put into the textbox I only get one value. Here is the code for adding the textboxes to the grid:
private void InsertEasyNums()
{
int x = 70;
int y = 40;
for (int i = 0; i < 9; i++)
{
if (i == 3)
{
x = 70;
y = 160;
}
else if(i == 6)
{
x = 65;
y = 280;
}
if (easyNums[i] == '0')
{
DrawingField.SendToBack();
int panelX = x + 300;
int panelY = y + + 100;
Font newFont = new Font("Arial", 25);
Point tbLocation = new Point(panelX, panelY);
userInput[i] = new TextBox();
userInput[i].Name = "Row[i]TB";
userInput[i].Font = newFont;
userInput[i].Width = 50;
userInput[i].Location = tbLocation;
userInput[i].BorderStyle = BorderStyle.None;
userInput[i].BackColor = DefaultBackColor;
Controls.Add(userInput[i]);
DrawingField.SendToBack();
x = x + 145;
DrawingField.SendToBack();
}
else if (easyNums[i] != '0')
{
DrawingField.SendToBack();
Font drawFont = new Font("Arial", 30, FontStyle.Bold);
Brush Numbers = new SolidBrush(Color.Black);
Graphics g = DrawingField.CreateGraphics();
g.DrawString(Convert.ToString(easyNums[i]), drawFont,
Numbers, x, y);
x = x + 146;
}
}
}
Here is where I try to print the Textboxes:
foreach (Control c in DrawingField.Controls)
{
if (c is TextBox)
{
int i = 0;
TextBox txt = (TextBox)c;
string str = txt.Text;
TBValues[i] = str;
i++;
}
}
foreach (var key in TBValues)
{
MessageBox.Show(key);
}
ANSWER: I moved the declaration of userInput to the beginning of the method and looped through 9 time to give 9 textboxes then used the if statements to move them and change properties.
try to move i before the loop
int i = 0;
foreach (Control c in DrawingField.Controls)
{
if (c is TextBox)
{
TextBox txt = (TextBox)c;
string str = txt.Text;
TBValues[i] = str;
i++;
}
}
foreach (var key in TBValues)
{
MessageBox.Show(key);
}

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

Dynamic textbox values to database

I am trying to insert values from dynamic textbox to database using Entity Framework in Web Forms.
On one click it make a table row with three column and every column has one textbox. Every another click is one row more.
public static int rowCnt = 0;
protected void BtnAddNewBuildItem_Click(object sender, EventArgs e)
{
// Current row count.
int rowCtr;
// Total number of cells per row (columns).
int cellCtr;
// Current cell counter
int cellCnt;
rowCnt = rowCnt + 1;
cellCnt = 3;
for (rowCtr = 1; rowCtr <= rowCnt; rowCtr++)
{
// Create new row and add it to the table.
TableRow tRow = new TableRow();
TableBuildItems.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "txtBuisniesItem_Row" + rowCtr + "Cell" + cellCtr;
// Add the control to the TableCell
tCell.Controls.Add(tb);
tRow.Cells.Add(tCell);
}
}
}
Then, on another button click i tried to insert one row values to database, but allways is empty string.
using (VODOMONTEntities context = new VODOMONTEntities())
{
BuildItem bi = new BuildItem();
for (int i = 0; i < rowCnt; i++)
{
TextBox tb1 = new TextBox();
tb1.ID = "txtBuisniesItem_Row" + (i + 1).ToString() + "Cell" + 1;
bi.Name = tb1.Text; //there is a empty string allways
context.BuildItems.Add(bi);
}
context.SaveChanges();
}
So, my question is how to insert a dynamic texbox values to database, like in this case?
Thank you!
protected void CreateNewBuild_Click(object sender, EventArgs e)
{
using (VODOMONTEntities context = new VODOMONTEntities())
{
Build b = new Build();
BuildItem bi = new BuildItem();
b.BuildSubject = txbSubject.Text;
b.BuildNumber = txbBuildNumber.Text;
b.City = txbCityBuild.Text;
// b.BuildDate = txbBuildDate.Text;
b.ClientId = Int32.Parse(ddlClient.SelectedValue);
context.Builds.Add(b);
for (int i = 0; i < (RowIndexNumber-1)/3; i++)
{
TextBox[] tb = new TextBox[RowIndexNumber];
tb[i*3] = new TextBox();
tb[i*3] = (TextBox)FindControl("txtBuisniesItem_Row" + (i * 3 + 1).ToString());
bi.Name = tb[i*3].Text;
tb[i*3+1] = new TextBox();
tb[i*3+1] = (TextBox)FindControl("txtBuisniesItem_Row" + (i * 3 + 2).ToString());
bi.Quantity = Convert.ToInt32(tb[i * 3 + 1].Text);
tb[i*3+2] = new TextBox();
tb[i*3+2] = (TextBox)FindControl("txtBuisniesItem_Row" + (i * 3 + 3).ToString());
bi.Price = decimal.Parse(tb[i * 3 + 2].Text.ToString());
bi.Build = b;
context.BuildItems.Add(bi);
context.SaveChanges();
}
}
}
public int RowIndexNumber = 1;
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtBuisniesItem_Row")).ToList();
foreach (string key in keys)
{
this.CreateTextBox("txtBuisniesItem_Row" + RowIndexNumber);
if (RowIndexNumber % 3 == 0)
{
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
RowIndexNumber++;
}
}
protected void BtnAddNewBuildItem_Click(object sender, EventArgs e)
{
int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtBuisniesItem_Row" + index);
this.CreateTextBox("txtBuisniesItem_Row" + (index + 1).ToString());
this.CreateTextBox("txtBuisniesItem_Row" + (index + 2).ToString());
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
txt.Attributes.Add("runat", "Server");
pnlTextBoxes.Controls.Add(txt);
}

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

dynamically create multiple textboxes 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");
}
}

Categories