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
Related
I wrote a program with C #
I have a combo box whose items are Binding from the database.I use AutoCompleteMode and AutoCompleteSource to search the combo box.But only when filtering does it find words whose first letter is the same as the input letter.While I need All items that contain these letters displayed.Is there a solution to this problem?
maybe this helps
// Example data
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
// Handle Text Box that you Fill
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.Tolower().Contains(comboBox1.Text.ToLower())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
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;
}
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;
}
}
In Visual Studio I have one ComboBox where I enter five items manually. (products) Also TextBox where I must write automatically the prices.
In array I save prices of these products and names:
string [] prodmas = new string[5];
prodmas[0] = "თევზი";
prodmas[1] = "პური";
prodmas[2] = "ყავა";
prodmas[3] = "შაქარი";
prodmas[4] = "წვენი";
double[] fasmas = new double[5];
fasmas[0] = 1.2;
fasmas[1] = 2;
fasmas[2] = 2.4;
fasmas[3] = 1.3;
fasmas[4] = 2.5;
How to do when I select item 1 in ComboBox, TextBox must show the item 1 price (1.2); when I select item3 TextBox must show the item 3 price (2.4)
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
.......
}
FULL CODE
string [] prodmas = new string[5];
double[] fasmas = new double[5];
void masivebi()
{
prodmas[0] = "თევზი";
prodmas[1] = "პური";
prodmas[2] = "ყავა";
prodmas[3] = "შაქარი";
prodmas[4] = "წვენი";
fasmas[0] = 1.2;
fasmas[1] = 2;
fasmas[2] = 2.4;
fasmas[3] = 1.3;
fasmas[4] = 2.5;
}
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
int index = produqcia.SelectedIndex;
fasi.Text = String.Format("The item {0} price {1}", index + 1, fasmas[index].ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
produqcia.DataSource = prodmas;
}
}
In form constructor or elsewhere:
comboBox1.DataSource = prodmas;
Selection event:
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
int index = comboBox1.SelectedIndex;
textBox1.Text = String.Format("The item {0} price {1}", index + 1, fasmas[index].ToString());
}
But this is not really good approach, better create object holding two of your values and bind it to combobox. Then cast selected item to your object and get needed value.
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.