how to save data from dynamic textbox? - c#

this code creates a textbox dynamically based on the total number of items in a listview. my problem is how can i access these textboxes so i can save the contents of the textbox to my database?
int f = 24;
int j = 25;
for (int gg = 0; gg < listView1.Items.Count;gg++ )
{
j = f + j;
TextBox txtb = new TextBox();
txtb.Name = "tboxl1"+gg;
txtb.Location = new Point(330,j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily,12);
groupBox2.Controls.Add(txtb);
}

I'd be more inclined to write you code like this:
var f = 24;
var j = 25;
var textBoxes =
Enumerable
.Range(0, listView1.Items.Count)
.Select(gg =>
{
j = f + j;
var txtb = new TextBox();
txtb.Name = String.Format("tboxl1{0}", gg);
txtb.Location = new Point(330, j);
txtb.Visible = true;
txtb.Enabled = true;
txtb.Font = new Font(txtb.Font.FontFamily, 12);
return txtb;
})
.ToList();
textBoxes.ForEach(txtb => groupBox2.Controls.Add(txtb));
Now you have a variable textBoxes that saves references to the new text boxes. You can use that to get the values from the text boxes to save them to your database.

If you want all TextBox controls then:
foreach (Control control in groupBox2.Controls)
{
if (control is TextBox)
{
string value = (control as TextBox).Text;
// Save your value here...
}
}
But if you want a specific TextBox, you can get it by its name like this:
Control control = groupBox1.Controls.Find("textBox1", false).FirstOrDefault(); // returns null if no control with this name exists
TextBox textBoxControl = control as TextBox; // if you want TextBox control
string value = control.Text;
// Now you can save your value anywhere

You can get the reference to text box as follows,
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}

Related

WinForms - Dynamically create textbox based on ComboBox selection

I am trying to create a TextBox based on the selection on ComboBox dynamically based on the following steps:
First step (Select a source from ComboBox):
Second step (Textbox should appear based on ComboBox.SelectedValue):
Last step (A new ComboBox should appear below):
I have created a createTextBox function using the following code:
public void createTextBox(int numPassenger)
{
TextBox[] passengerBoxes = new TextBox[numPassenger];
for (int u = 0; u < passengerBoxes.Count(); u++)
{
passengerBoxes[u] = new TextBox();
}
int i = 0;
foreach (TextBox txt in passengerBoxes)
{
string name = "passenger" + i.ToString();
txt.Name = name;
txt.Text = name;
txt.Location = new Point(244, 32 + (i * 28));
txt.Visible = true;
this.Controls.Add(txt);
i++;
}
}
Is there a way that I can modify my current function to adapt to the mentioned steps? Additionally, how can I find the dynamically created TextBox?
You can try the following code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
createTextBox(sender as ComboBox);
}
private void createTextBox(ComboBox cmb)
{
TextBox passengerBoxes = new TextBox();
string name = cmb.Text;
if (Controls.Find(name, true).Length == 0)
{
passengerBoxes.Name = name;
passengerBoxes.Text = name;
int textBoxCount = GetTextBoxCount();
passengerBoxes.Location = new Point(244, 32 + (textBoxCount * 28));
passengerBoxes.Visible = true;
this.Controls.Add(passengerBoxes);
if (cmb.Items.Count != 1)//last item remaining then we should not create new combo box
{
ComboBox newCombo = new ComboBox
{
Location = new Point(cmb.Location.X, 32 + ((textBoxCount + 1) * 28))
};
foreach (string str in cmb.Items)
if (cmb.Text != str)
newCombo.Items.Add(str);
newCombo.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
this.Controls.Add(newCombo);
}
}
else
MessageBox.Show("Textbox Already for the selected source " + name);
}
private int GetTextBoxCount()
{
int i = 0;
foreach (Control ctl in this.Controls)
{
if (ctl is TextBox) i++;
}
return i;
}

C# Error when searching for control in UpdatePanel

I have a little problem. First of all, some info:
- On my page, I have an UpdatePanel with a button inside it.
- When you click this button, I generate a new row with dropdown lists. Each time I have to generate a table from scratch, because it resets after the click, so I update [ViewState] value and generate as many rows as clicks.
- Outside the panel, I have another button. After clicking this button, I want to collect data from drop-down lists. To do it, I have to get to these controls.
I tried to use function FindControl(), but I guess I can't - as far as I know, it does not perform a deep search. This means I have to pass as a parameter the exact container with this control. Because control is inside the table, I should get to the <td> value and I can't do that (<td> does not have ID - yes, I can add it but <td> is also dynamically created. That means I would need to get first to <td>, then to my control (guess what - <tr> is also created dynamically).
Because I can't use FindControl function, I use FindRecursiveControl function (code below) The problem is, that this function neither finds anything. Any suggestions about what might be the reason? I added this whole info in case that the reason is for example usage of UpdatePanel and page life cycle.
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID)
{
return rootControl;
}
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null)
{
return controlToReturn;
}
}
return null;
}
My usage of this function:
string control_id = "parametr" + i;
DropDownList dropdown = (DropDownList)FindControlRecursive(UpdatePanel1, control_id);
Script generating table in UpdatePanel after button click
protected void generuj_tabele(int il_klik)
{
il_par.Text = "Ilość parametrów: " + il_klik.ToString();
TableRow table_head = new TableRow();
table_head.Attributes.Add("class", "w3-green");
Table1.Rows.Add(table_head);
for (int j = 0; j < 5; j++)
{
TableCell cell = new TableCell();
table_head.Cells.Add(cell);
}
Table1.Rows[0].Cells[0].Text = "Parametr";
Table1.Rows[0].Cells[1].Text = "Wartość początkowa";
Table1.Rows[0].Cells[2].Text = "Inkrementacja?";
Table1.Rows[0].Cells[3].Text = "Zwiększ o:";
Table1.Rows[0].Cells[4].Text = "Zwiększ co:";
RootObject obj = (RootObject)Session["get_offer"];
for (int i = 0; i < il_klik; i++)
{
parametr = new DropDownList();
wartosc = new TextBox();
inkrementacja = new CheckBox();
inkrementacja_numer = new TextBox();
skok = new TextBox();
//inkrementacja_numer.Enabled = false;
// skok.Enabled = false;
inkrementacja_numer.Attributes.Add("Type", "number");
skok.Attributes.Add("Type", "number");
//inkrementacja.CheckedChanged += new EventHandler((s, eventarg) => checkbox_change(s, eventarg, i));
//inkrementacja.AutoPostBack = true;
//parametr.AutoPostBack = true;
TableRow row = new TableRow();
Table1.Rows.Add(row);
parametr.EnableViewState = true;
wartosc.EnableViewState = true;
inkrementacja.EnableViewState = true;
inkrementacja_numer.EnableViewState = true;
skok.EnableViewState = true;
for (int j = 0; j < 5; j++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
}
Table1.Rows[i + 1].Cells[0].Controls.Add(parametr);
Table1.Rows[i + 1].Cells[1].Controls.Add(wartosc);
Table1.Rows[i + 1].Cells[2].Controls.Add(inkrementacja);
Table1.Rows[i + 1].Cells[3].Controls.Add(inkrementacja_numer);
Table1.Rows[i + 1].Cells[4].Controls.Add(skok);
if (i == il_klik - 1)
{
wystaw_liste(obj);
Price pr = obj.sellingMode.price;
parametr.Items.Add(pr.amount.ToString());
List<Parameter> par = obj.parameters;
foreach (Parameter p in par)
{
List<string> val = p.values;
if (val.Count() > 0)
{
foreach (string v in val)
{
parametr.Items.Add(v);
}
}
}
foreach (string p in parametry_list)
{
parametr.Items.Add(p);
}
parametry_list.Clear();
}
parametry.Add(parametr);
wartosci.Add(wartosc);
inkrementacje.Add(inkrementacja);
inkrementacje_numery.Add(inkrementacja_numer);
skoki.Add(skok);
if (i == il_klik - 1)
{
Session["v_parametr"] = parametry;
Session["v_wartosc"] = wartosci;
Session["v_inkrementacja"] = inkrementacje;
Session["v_ink_nr"] = inkrementacje_numery;
Session["v_skok"] = skoki;
}
parametr.ID = "parametr" + i;
wartosc.ID = "wartosc" + i;
inkrementacja.ID = "inkrementacja" + i;
inkrementacja_numer.ID = "inkrementacja_numer" + i;
skok.ID = "skok" + i;
}
}
When I try to check parameters of DropDownList (e.g. SelectedValue) I get error "Object reference not set to an instance of an object"

Check if textbox has same value to other textbox

I want to check if there are similar value in my textboxes, I have 10 Textboxes, and on button click I want to validate if there are the same vales
for (int c = 1; c <= 10; c++)
{
TextBox check_subjName = table_textboxes.FindControl("subject_name" + c.ToString()) as TextBox;
for (int b = 1; b <= 10; b++)
{
TextBox check_subjName2 = table_textboxes.FindControl("subject_name" + b.ToString()) as TextBox;
if (c != b)
{
if (check_subjName.Text == check_subjName2.Text)
{
//there are similar values
}
}
}
}
So it is valid if all textboxes have different values. You could use LINQ:
List<string> textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim())
.ToList();
var distinctTexts = new HashSet<string>(textList);
bool allDifferent = textList.Count == distinctTexts.Count;
here a slightly optimized approach (in this case micro optimization):
var textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim());
HashSet<string> set = new HashSet<string>();
bool allDifferent = textList.All(set.Add);

How to access multiple buttons or textbox or any control?

I want to access multiple textbox name textbox1,textbox2,textbox3, etc.. by loop not by individual name. For that reason I created one function which create this var names.
public string[] nameCre(string cntrlName, int size)
{
string[] t = new string[size];
for (int i = 0; i < size; i++)
{
t[i] = cntrlName.ToString() + (i + 1);
}
return t;
}
for nameCre("Textbox",5); So this,function successfully returning me TextBox1, TextBox2 ... TextBox5.
But when I am trying to convert this string to TextBox control by
string[] t = new string[50];
t= nameCre("TextBox",5);
foreach (string s in t)
{
((TextBox) s).Text = "";
}
it giving me error :
Cannot convert type 'string' to 'System.Windows.Forms.TextBox'....
How can I accomplish this job?
var t = nameCre("TextBox",5);
foreach (var s in t)
{
var textBox = new TextBox {Name = s, Text = ""};
}
string[] t= new string[50];
t= nameCre("TextBox",5);
foreach (string s in t){
TextBox tb = (TextBox)this.Controls.FindControl(s);
tb.Text = "";
}
if you have many text boxes
foreach (Control c in this.Controls)
{
if (c.GetType().ToString() == "System.Windows.Form.Textbox")
{
c.Text = "";
}
}
Perhaps you need this -
string[] t = new string[50];
t = nameCre("TextBox", 5);
foreach (string s in t)
{
if (!string.IsNullOrEmpty(s))
{
Control ctrl = this.Controls.Find(s, true).FirstOrDefault();
if (ctrl != null && ctrl is TextBox)
{
TextBox tb = ctrl as TextBox;
tb.Text = "";
}
}
}
This post is quite old, anyway I think I can give you (or anyone else with a problem like that) an answer:
I think using an Array (or List) of TextBoxs would be the best solution for doing that:
// using an Array:
TextBox[] textBox = new TextBox[5];
textBox[0] = new TextBox() { Location = new Point(), /* etc */};
// or
textBox[0] = TextBox0; // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Length; i++)
{
textBox[i].Text = "";
}
// using a List: (you need to reference System.Collections.Generic)
List<TextBox> textBox = new List<TextBox>();
textBox.Add(new TextBox() { Name = "", /* etc */});
// or
textBox.Add(TextBox0); // if you already have a TextBox named TextBox0
// loop it:
for (int i = 0; i < textBox.Count; i++)
{
textBox[i].Text = "";
}
I hope this helps :)

Hiddenfield WebControl

foreach (var item in AnketSoru)
{
r = new HtmlTableRow();
c = new HtmlTableCell();
c.InnerHtml = item.new_question_text.ToString();
r.Cells.Add(c);
switch (item.new_question_type.ToString())
{
case "2": //FreeText
c = new HtmlTableCell();
TxtFreeText = new TextBox();
TxtFreeText.ID = "Txt_" + item.new_survey_questionid.ToString();
TxtFreeText.TextMode = TextBoxMode.MultiLine;
TxtFreeText.Width = 300;
TxtFreeText.Height = 50;
TxtFreeText.EnableViewState = true;
c.Controls.Add(TxtFreeText);
HiddenField txthfield = new HiddenField();
txthfield.Value = item.new_name.ToString();
c.Controls.Add(txthfield);
and
foreach (Control c in plc.Controls)
{
System.Web.UI.HtmlControls.HtmlTable Survey_Inner = (System.Web.UI.HtmlControls.HtmlTable)c.FindControl("Survey_Inner");
foreach (System.Web.UI.HtmlControls.HtmlTableRow r in Survey_Inner.Rows)
{
foreach (Control ctr in r.Cells)
{
foreach (Control ct in ctr.Controls)
{
if (ct.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
string freeTxtQues = ?? ;
string TextCevap = ((System.Web.UI.WebControls.TextBox)ct).Text;
string deger = ct.ID.ToString();
Guid QuestionId = new Guid(deger.Substring(4));
SaveAnswers(this._PortalUserHelper.UserProxy.ContactId, EgitimKatilimcisi, QuestionId, TextCevap, freeTxtQues);
}
i tryed
string freeTxtQues = ((System.Web.UI.WebControls.HiddenField)ct).Value;
but returns me error. "InvalidCastException was unhandled by user code."
'System.Web.UI.WebControls.TextBox' türündeki nesne 'System.Web.UI.WebControls.HiddenField' türüne atılamadı.
I'm trying to reach hiddenfields value's and set them to the freeTxtQues value but couldn't able to do it for now. Any help for how can i do that?
Hard to understand your question/problem but I will throw something...
When you create dynamic controls you need to create them on Init event so when ViewState is applied he finds the controls and sets their values. If you are not creating the controls in Init but later, you will found out that the control doesn't have the supposed value!

Categories