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);
}
Related
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();
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);
}
i currently have a form which i dynamically created a 2D array of textboxes, buttons etc. i just found out my other parts of the program cannot access to the textboxes i created? is there a way i can do it?
my codes goes something like:
public Form1()
{
int column = 4;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
/////fill the textboxes with data//////
}
i cannot access the textbox outside the method, how can i do it? can you provide some working coded? i am still relatively new to c#, thank you very much
You could add a class level property just like
public class Form1
{
public System.Windows.Forms.TextBox[,] textbox { get; set; }
public Form1()
{
int column = 4;
textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
}
}
Then you can simply do like
Form1 myForm = GetMyForm();
System.Windows.Forms.TextBox[,] theTextboxArray = myForm.textbox;
Surely you can't access them with textbox_i_j where i & j are numerals with intellisense because its not supported but you can get them like this
TextBox GetTB(string name)
{
return ( Controls.FindControl(name) as TextBox );
}
Declare int column = 4;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
outside of Form1 constructor. Your code should look like:
int column = 4;
System.Windows.Forms.TextBox[,] textbox;
public Form1()
{
textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
}
}
/////fill the textboxes with data//////
}
i have search the net for answers while i wait for some smart people to answer my questions. i use a dictionary to retrieve the text box, goes something like this:
Get a Windows Forms control by name in C#
//declaration
Dictionary <String, System.Windows.Forms.TextBox> dictionaryTextBox = new Dictionary<string, System.Windows.Forms.TextBox>();
// creation of array
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
textbox[i, j] = new System.Windows.Forms.TextBox();
textbox[i, j].Size = new Size(80, 20);
textbox[i, j].Name = "textbox_" + i + "_" + j;
textbox[i, j].Location = new System.Drawing.Point((i * 80) + 20, (j * 20) + 30);
textbox[i, j].Visible = true;
Controls.Add(textbox[i, j]);
//new added
dictionaryTextBox.Add (textbox[i, j].Name, textbox[i, j]);
}
}
// retrieval
System.Windows.Forms.TextBox retrieve = dictionaryTextBox["textbox_3_3"];
retrieve.Text = "apple";
I am new to programming, working in asp.net.
I made a table with iteration, and here is my code:
int row2 = Convert.ToInt32(Request.QueryString["coll"]);
Session.Add("sumColl", row2);
TableRow tr2;
TableCell tc2;
TextBox tb2;
RequiredFieldValidator rfv;
for (int j = 0; j < row2; j++)
{
tr2 = new TableRow();
tc2 = new TableCell();
tc2.Controls.Add(new LiteralControl((j + 1).ToString()));
tr2.Cells.Add(tc2);
tc2 = new TableCell();
tb2 = new TextBox();
tb2.ID = "name" + (j + 1).ToString();
btn = new Button();
btn.ID = "search" + (j + 1).ToString();
btn.Text = "Search";
btn.OnClientClick = "javascript:openChild('popupA.aspx?dest=" + tb2.ID + "','win2')";
btn.CausesValidation = false;
rfv = new RequiredFieldValidator();
rfv.ID = "rfvR" + (j + 1).ToString();
rfv.ControlToValidate = tb2.ID;
rfv.Display = ValidatorDisplay.Dynamic;
rfv.ErrorMessage = "**";
tc2.Controls.Add(tb2);
tc2.Controls.Add(btn);
tc2.Controls.Add(rfv);
tr2.Cells.Add(tc2);
tblA.Rows.Add(tr2);
}
I want to get values from the database, where the input came from the textbox in the table above.
After I get the values I want to sum them.
The problem is I don't know how to get the input from iteration above.
I did something like below code.
int sumsColl = Convert.ToInt32(Session["sumColl"]);
double sum_coll = 0;
for (int j = 0; j < sumsColl; j++)
{
TextBox tb2 = new TextBox();
tb2 = this.Page.FindControl("name" + (j + 1).ToString()) as TextBox;
if (tb2 != null)
{
string sqlCol2 = "select p from somewhere where nameColl = '" + tb2.Text + "'";
DataTable dtcol2 = db.setDataTableSQL(sqlCol2);
for (int i = 0; i < j; i++)
{
Session.Add("P" + (j + 1).ToString(), dtcol2.Rows[0]["p"]);
}
sum_coll = sum_coll + Convert.ToDouble(Session["P"+(j + 1).ToString()]);
}
}
if (sum_coll < value)
{
Msg.Text = "Error . " + Msg.Text;
valid = false;
}
I know this is a mess, please help me and let me know if you need another clue.
I don't know what you are trying to do. Try DataGrid or DataGridView, ListView controls to display data. Your code seems very complicated. There are controls out there that specifically displays tabular data.
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");
}
}