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;
}
Related
I want to change the background of some labels depending on what is written on a text file:
private void Form3_Load(object sender, EventArgs e)
{
string[] words = new string[7];
StreamReader read = new StreamReader(path);
while(!read.EndOfStream)
{
string line = read.ReadLine();
words = line.Split(';');
if(words[6] == "no")
{
//-----What I have to write here---
}
}
read.Close();
}
There are over 50 labels named "lbl101","lbl102","....","lbl150"
try it:
if(words[6] == "no")
{
int count = 150;
for (int a = 1 ; a < count; a++)
{
Label currentLabel = (Label)this.Controls.Find("lbl"+a,true)[0];
//change color of currentLabel
}
}
There's the working solution:
private void Form3_Load(object sender, EventArgs e)
{
int count = 101;
string[] words = new string[7];
StreamReader read = new StreamReader(pathRooms);
while(!read.EndOfStream)
{
string line = read.ReadLine();
words = line.Split(';');
if (words[6] == "no")
{
Label currentLabel = (Label)this.Controls.Find("lbl" + count, true)[0];
currentLabel.BackColor = Color.Yellow;
}
count = count + 1;
}
read.Close();
}
You can iterate all over them using OfType<T>() method on Controls collection of form like:
if(words[6] == "no")
{
foreach(var label in this.Controls.OfType<Label>().Where(x=>x.Name.Contains("lbl")))
{
label.Text = "Some Text";
}
}
This will only work on the labels that are direct child of form, labels nested inside other user controls or nested panels will not be affected, for that you have to do it recursively.
Loop through the Controls collection of the form checking for Label objects. Then, amend accordingly as per the specified value.
1.) Create a List with all the labels.
Label lbl101 = new Label();
Label lbl102 = new Label();
...
List<Label> labels = new List<Label>()
{
lbl101,
lbl102
...
};
2.) If your words[] string is the name of the color you can write:
if(words[6] == "no")
{
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml(words[..]);
foreach(Label l in Labels)
{
l.BackColor = myColor;
}
}
I am able to add textboxes dynamically and i am not able to use the value of the textboxes which are dynamically added
Here is my code
int i = 0;
List<string> controlidlist = new List<string>();
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
controlidlist = (List<string>)ViewState["controlidlist"];
foreach (string Id in controlidlist)
{
i++;
TextBox tb = new TextBox();
tb.ID = Id;
LiteralControl lineBreak = new LiteralControl();
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(lineBreak);
}
}
Here am performing the dynamically adding the textboxes
protected void Button1_Click(object sender, EventArgs e)
{
i++;
TextBox tb = new TextBox();
tb.ID = "textboxes" + i;
tb.Text = "textbox" + i;
LiteralControl lineBreak = new LiteralControl("<br>");
PlaceHolder1.Controls.Add(tb);
PlaceHolder1.Controls.Add(lineBreak);
controlidlist.Add(tb.ID);
ViewState["controlidlist"] = controlidlist;
}
Here i want to try get the textbox values which are dynamically added
protected void datainput_Click(object sender, EventArgs e)
{
string m = string.Empty;
for (int f = 0; f < i; f++)
{
TextBox t = (TextBox)FindControl("textboxes"+f);
string k = t.Text;
m = m +","+k;
}
string h = m;
}
The error which am getting is
"Object reference not set to an instance of an object".
at string k = t.Text;
Add it to a container:
<asp:Panel runat="server" ID="pnlTextboxes"></asp:Panel>
foreach (string Id in controlidlist)
{
i++;
TextBox tb = new TextBox();
tb.ID = Id;
LiteralControl lineBreak = new LiteralControl();
pnlTextboxes.Controls.Add(tb);
pnlTextboxes.Controls.Add(lineBreak);
}
and :
TextBox t = (TextBox)pnlTextboxes.FindControl("textboxes"+f);
UPDATE:
TextBox t = (TextBox)PlaceHolder1.FindControl("textboxes"+f);
Behind the code C#, when the user select 3(dropdownlist) then press execute button, it will auto generate 3 textboxes. After user fill out names on 3 textboxes then click request button, I want the 3 names that user entered display on different result textbox. How do I do that?
Here are C# codes,
protected void ExecuteCode_Click(object sender, EventArgs e)
{
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
div1.Controls.Add(div);
}
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
foreach (Control c in phDynamicTextBox.Controls)
{
try
{
TextBox t = (TextBox)c;
// gets textbox ID property
//Response.Write(t.ID);
str = t.Text;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
Then HTML codes,
<div id="div1" runat="server">
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
</div>
you cannot access to control that create dynamically on postback, but you can try get input value from request like this
protected void ExecuteCode_Click(object sender, EventArgs e)
{
List<string> tbids = new List<string>();
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
phDynamicTextBox.Controls.Add(div);
tbids.Add(t.ID);
}
Session["tbids"] = tbids;
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
var tbids = (List<string>)Session["tbids"];
foreach (var id in tbids)
{
try
{
str += Request[id]+" "; //here get value tb with id;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
One option is:
when you create the textbox you save the Id in a list in session, then you through the list and use it:
TextBox myTextbox = (TextBox)FindControl("name");
example:
List<string> list = (List<string>)Session["myList"];
TextBox myTextbox;
foreach (string item in list)
{
myTextbox = (TextBox)FindControl(item);
//in myTextbox you have the atribute Text with the informatcion
}
Sorry for my english.
I'm making a windowsform with dynamically created textboxes as u see in the method.
public void createPassengerBoxes(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++;
}
}
}
How do I access the text from the boxes?
While I'm not sure at what point, or based on what action, you'd like to fetch the data, here's very generic method:
private String[] GetTextBoxStrings()
{
List<String> list = new List<String>();
foreach (Control c in this.Controls)
{
if (c is TextBox)
list.Add(((TextBox)c).Text);
}
return list.ToArray();
}
Move your textbox declaration outside of the function. This makes it accessible from other functions within the class:
class MyFormsClass
{
// declare textboxes at class level
TextBox[] passengerBoxes;
public void createPassengerBoxes(int numPassenger)
{
passengerBoxes = new TextBox[numPassenger];
...
}
public void OnButtonClick(...)
{
if (passengernBoxes != null)
{
foreach (TextBox txt in passengerBoxes)
{
// do something with textboxes
}
}
}
...
}
You could also use Lambda:
var strings = Controls.OfType<TextBox>()
.Select(c => c.Text)
.ToList();
this only work if ou have no nested controls - e.g. a pannel or a group that holds some textBoxes
How can store name of dynamically created checkbox in a String array when I don't know how many checkbox will user select at runtime.
Say I have 10 dynamic checkboxes and out of 10 user select 6 checkboxes randomly now how can get the name of those selected checkboxes and store them in a String array.
I know how to use event handler on dynamic check box but confused how to declare Straing array when I don't know what will be be size of an array.
Here what I have done till now -
private void CheckBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//Label myLabel;
String str = null;
if (c.Checked == true)
{
str = c.Text;
gpBox[gpcount] = new GroupBox();
gpBox[gpcount].Name = "gpBox" + Convert.ToString(count);
gpBox[gpcount].Text = str;
gpBox[gpcount].Location = new Point(5, gpposition);
gpBox[gpcount].AutoSize = true;
this.Controls.Add(gpBox[gpcount]);
aCommand3 = new OleDbCommand("select * from batch_tbl where batch_branch LIKE '" + str + "'", main_connection);
aAdapter3 = new OleDbDataAdapter(aCommand3);
ds3 = new DataSet();
aAdapter3.Fill(ds3, "app_info");
ds3.Tables[0].Constraints.Add("pk_bno", ds3.Tables[0].Columns[0], true);
int batch_count = ds3.Tables[0].Rows.Count;
batchCheckBox = new CheckBox[batch_count];
//filling the groupbox with batch code by generating dynamic checkboxes
for (int j=0; j < batch_count; ++j)
{
batchCheckBox[j] = new CheckBox();
batchCheckBox[j].Name = "batch" + Convert.ToString(k);
batchCheckBox[j].Text = ds3.Tables[0].Rows[j][1].ToString();
Console.WriteLine(batchCheckBox[j].Text);
batchCheckBox[j].Location = new System.Drawing.Point(104 * position, 30);
gpBox[gpcount].Controls.Add(batchCheckBox[j]);
batchCheckBox[j].CheckStateChanged += new System.EventHandler(BatchBoxCheckedChanged);
position++;
count++;
Console.WriteLine(batchCheckBox[j].Name);
k++;
}
position = 1;
gpposition += 100;
}
else
{
count--;
this.Controls.RemoveByKey("lbl" + c.Name);
this.Update();
}
}
int total_batch = 1;
string[] batchname;
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
batchname = new String[total_batch];
total_batch++;
}
else
{
}
}
You can try this:
//Gets all checkbox's on the form
List<CheckBox> chks = Controls.OfType<CheckBox>().ToList();
//take only those who is checked, and select only their name property
List<string> names = chks.Where(c => c.Checked).Select(c => c.Name).ToList();
UPDATE
For testing you could print a list of the selected names:
string txt = "";
foreach(string name in names)
{
txt += name+" \n\r";
}
MessageBox.Show(txt);
Thank you everbody
}
list = new List<string>();
}
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
list.Add(batchBox.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(string prime in list) // Loop through List with foreach
{
Console.WriteLine(prime);
}
}
This is Done