Dynamic textbox values to database - c#

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

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

Cant fetch the ID of dynamically created Textboxes. Any solution?

I am unable to get the ID of dynamically generated textboxes. Hence I cant get their values. Posting my code below . Please help .
protected void txt_Freq_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int rem = Convert.ToInt16(ddl_freq.SelectedItem.Value.ToString());
Table tbl1 = new Table();
form1.Controls.Add(tbl1);
for (i = 1; i <= rem; i++)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
TextBox tb = new TextBox();
tb.ID = "rem" + i.ToString();
Label lb = new Label();
CalendarExtender calex = new CalendarExtender();
calex.ID = "calexRem" + i.ToString();
calex.TargetControlID = "rem" + i.ToString();
DropDownList txt_Time_rem = new DropDownList();
txt_Time_rem.ID = "ddl" + i.ToString();
for (int hr = 0; hr <= 23; hr++)
{
for (int min = 0; min < 60; min += 15)
{
if (hr <= 9 && min == 0)
txt_Time_rem.Items.Add(new ListItem('0' + hr.ToString() + ':' + '0' + min.ToString()));
else if (hr <= 9 && min != 0)
txt_Time_rem.Items.Add(new ListItem('0' + hr.ToString() + ':' + min.ToString()));
else if (hr > 9 && min == 0)
txt_Time_rem.Items.Add(new ListItem(hr.ToString() + ':' + '0' + min.ToString()));
else
txt_Time_rem.Items.Add(new ListItem(hr.ToString() + ':' + min.ToString()));
}
}
txt_Time_rem.Items.Insert(0, new ListItem("Time"));
lb.Text = "Reminder " + i.ToString();
cell.Controls.Add(lb);
cell.Controls.Add(tb);
cell.Controls.Add(calex);
cell.Controls.Add(txt_Time_rem);
row.Cells.Add(cell);
tbl1.Rows.Add(row);
Response.Write(tb.ID);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btntemp_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
for(x=1;x<=Convert.ToInt16(ddl_freq.SelectedItem.Value.ToString());x++)
{
TextBox txtUserName = form1.FindControl("rem"+x.ToString()) as TextBox;
if (txtUserName != null)
{
Response.Write("ID found!");
}
else
{
Response.Write("Failed");
}
I have tried replacing form1 with Page.Master as I have a Master Page but nothing works. It will print "Failed". Please Help.

Dynamic rows on table c#

two part question:
1:
I am using a session state refresh to hold count of the page reloads but when using a series of if statements the validation isn't working. Code at the bottom. What am I doing wrong?
2:
Using session state against postback doesn't appear to be the most efficient method of doing this, if I added another table with the same functionality, the count would affect both tables.
For example if I only wanted people to be able to add a maximum of three rows to a table, on two tables, they would only be able to add four rows in total.
What would be a better method of storing a count for separate refreshes?
Update
I have found the issue with the code not adding rows to the existing but I'm unsure of how to fix it.
Basically each iteration is deleting the existing row then adding a single row again. So there will never be more than one row.
Any ideas?
namespace FormTest
{
public partial class About : Page
{
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["count"] = 0;
}
else
{
int count = (int)Session["count"];
count++;
Session["count"] = count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int rows = 1;
int cols = 4;
if ((int)Session["count"] == 0)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 1)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 2)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
if ((int)Session["count"] == 3)
{
for (int i = 0; i < rows; i++)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}
}
}
}//end cmdCreate_Click
}
}
You don't need a list of if conditions, you just need to ensure the number of rows is less than your desired limit. You also should store the limit per table to avoid your count clashing if/when more tables are added.
This is how I would do it:
(note: This won't work "as-is" - I've assumed you've removed the code to assign tbl within cmdCreate_Click()and have left it as is for clarity)
namespace FormTest
{
public partial class About : Page
{
private int myFirstTableMaxRows = 3;
protected void Page_Load(object sender, System.EventArgs e)
{
tbl.BorderStyle = BorderStyle.Inset;
tbl.BorderWidth = Unit.Pixel(1);
if (!Page.IsPostBack)
{
Session["myFirstTable_count"] = "0";
}
else
{
int count = (int)Session["myFirstTable_count"];
Session["myFirstTable_count"] = ++count;
}
}
protected void cmdCreate_Click(object sender, System.EventArgs e)
{
tbl.Controls.Clear();
int cols = 4;
int currentRowCount = (int)Session["myFirstTable_count"];
if(currentRowCount <= myFirstTableMaxRows)
{
TableRow rowNew = new TableRow();
tbl.Controls.Add(rowNew);
for (int j = 0; j < cols; j++)
{
TableCell cellNew = new TableCell();
Label lblNew = new Label();
lblNew.Text = "(" + i.ToString() + "," + j.ToString() + ")<br />";
TextBox tbNew = new TextBox();
cellNew.Controls.Add(lblNew);
cellNew.Controls.Add(tbNew);
rowNew.Controls.Add(cellNew);
}
}
else
{
Response.Redirect("http://www.google.co.uk");
}
}//end cmdCreate_Click
}
Update after question edit
The existing rows will go due to this line in the code:
tbl.Controls.Clear();
The table is being cleared, then a single row is added per the logic in the cmdCreate_Click() method.

How to get a Value from Table Iteration in C#

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.

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