Retrieve value from dynamic TextBox - c#

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.
}
}

Related

Dynamically generating textboxes asp.net

I have created a function to dynamically create textboxes based on the amount selected from the textbox, additionally I'm using these textboxes to display data from database. However when the user chooses for exactly five from the dropdownlist, and three textboxes was already there, instead of adding 2 more textboxes, it adds the additional 5 textboxes. What I do in order to just add the additionaly textboxes?
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
public void populate()
{
int count = Convert.ToInt32(TotalSeal.SelectedItem.Value);
for (int i = 0; i < count; i++)
{
if (i < 0)
{
}
else
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
}
UPDATE
public void populate()
{
//ControlCache = new List<Control>();
//phSealNum.Controls.Clear();
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
int currentItems = phSealNum.Controls.OfType<TextBox>().Count();
int totalitems = targetCount - currentItems;
if (totalitems <= 7)
{
for (int i = 0; i < totalitems; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}
else
{
lblError.Text = targetCount + " exceeds number of seals";
}
}
Using #indrit-kello logic should be like this:
protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
public void populate()
{
int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
if(targetCount > 7)
targetCount = 7;
int currentItems = 0;//TODO
for (int i = currentItems; i < targetCount; i++)
{
TextBox tx = new TextBox();
tx.MaxLength = 10;
tx.Width = 100;
phSealNum.Controls.Add(tx);
phSealNum.Controls.Add(new LiteralControl(" "));
ControlCache.Add(tx);
}
}

I want to create an array of labels and sort them according to the values in the labels using insertion sort

I am taking input from 5 textboxes and sorting the values inserted into the text boxes by putting them into labels and moving the labels around till the values in them are sorted.
I have so far put them into labels, but I don't know how to move he labels on button click and let the labels move to get sorted.
This is one way of simulating the algorithm of insertion sort.
my code so far for button click :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
myLabel[0].Text = textBox1.Text;
myLabel[1].Text = textBox5.Text;
myLabel[2].Text = textBox4.Text;
myLabel[3].Text = textBox3.Text;
myLabel[4].Text = textBox2.Text;
}
public partial class Form1 : Form
{
Label[] myLabel=new Label[5];
int a = 30; //x coordinates of first label in label1 array
int b = 125; //y coordinates of first label in label1 array
int c = 0;
int k = 0;
int n = 0;
int j = 1;
int i;
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Selection Sort");
comboBox1.Items.Add("Insertion Sort");
}
you need to sort value of textbox and then put value in labels. Something like this :
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "insertion sort")
{
for ( i = 0; i < 5; i++)
{
if (c != 0)
{
myLabel[i].Dispose();
}
myLabel[i] = new Label();
myLabel[i].Location = new Point(a, b);
myLabel[i].Width = 70;
myLabel[i].Height = 70;
myLabel[i].BackColor=Color.White;
myLabel[i].BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(myLabel[i]);
a = a + 100;
myLabel[i].Visible = true;
}
timer1.Start();
c++;
}
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>(textBox1.Text, textBox1.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox2.Text, textBox2.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox3.Text, textBox3.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox4.Text, textBox4.Text.Value));
list.Add(new KeyValuePair<string, string>(textBox5.Text, textBox5.Text.Value));
list.Sort(Compare2);
int increment = 0;
foreach(var item in list)
{
myLabel[increment].Text=item.Value;
increment++;
}
}
static int Compare2(KeyValuePair<string, string> a, KeyValuePair<string, string> b)
{
return a.Value.CompareTo(b.Value);
}

how i do create find similar excel?

i want create search in form similar EXCEL , find and put (row) in listview
this my form :
and my code :
private int searchIndex = -1;
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Find Next";
try
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
searchIndex = (searchIndex + 1) % dataGridView1.Rows.Count;
DataGridViewRow row = dataGridView1.Rows[searchIndex];
if (row.Cells["Product"].Value == null)
{
continue;
}
if (row.Cells["Product"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Product"].Value.ToString().Trim().Contains(textBox1.Text))
{
ListViewItem lvi = new ListViewItem(row.Cells["Product"].Value.ToString());
lvi.SubItems.Add(row.Cells["Product"].Value.ToString());
listView1.Items.Add(lvi);
dataGridView1.CurrentCell = row.Cells["Product"];
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[row.Index].Index;
row = dataGridView1.Rows[i];
return;
}
}
}
catch { }
}
and in textbox1_textchanged :
searchIndex = -1;
button1.Text = "Find";
listView1.Clear();
I want when search end, send message ...
thanks
Mimicking the Find All functionality, populating your ListView will be very similar to the Find Next functionality. Here's an example if it were a separate button from Find Next:
public Form1()
{
InitializeComponent();
listView1.View = View.Details;
listView1.Columns.Add("Column");
listView1.Columns.Add("Row");
listView1.Columns.Add("Value");
}
private void button2_Click(object sender, EventArgs e)
{
button2.Text = "Find All";
int tempIndex = -1;
listView1.Items.Clear();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tempIndex = (tempIndex + 1) % dataGridView1.Rows.Count;
DataGridViewRow row = dataGridView1.Rows[tempIndex];
if (row.Cells["Foo"].Value == null)
{
continue;
}
if (row.Cells["Foo"].Value.ToString().Trim().StartsWith(textBox1.Text) || row.Cells["Foo"].Value.ToString().Trim().Contains(textBox1.Text))
{
DataGridViewCell cell = row.Cells["Foo"];
ListViewItem lvRow = new ListViewItem(new string[] { cell.ColumnIndex.ToString(), cell.RowIndex.ToString(), cell.Value.ToString() });
listView1.Items.Add(lvRow);
}
}
MessageBox.Show("Search ended."); // Or whatever message you intend to send.
}

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...

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