Looping through labels with similar name C# - c#

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

Related

Advanced item search in combobox C#

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

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

How to make if statement for multiple elements? C#

I am using VS2017 and C# on Windows Forms.
I'm creating a little tool and I need some assistance.
I have 10 text boxes, names textGame1, textGame2, textGame3, etc etc
I want to create code, in which if the any of the text boxes are empty, then it will replace the textbox text to "EMPTY".
I could easily do
if (string.IsNullOrWhiteSpace(textGame1.Text))
{
textGame1.Text = "EMPTY";
}
However I would have to create 10 of those for each text box.
Is there a simpler way, than to create 10 of these IF statements?
First, create a collection to store each text box you want to manipulate. You can do this by hand:
var textBoxes = new[] { textGame1, textGame2, textGame3, ... };
Or using the Controls collection (a little Linq can help):
var textBoxes = Enumerable.Range(1, 10).Select(i => (TextBox)Controls[$"textGame{i}"]);
Or if you need to search all children recursively, use the Find method:
var textBoxes = Enumerable.Range(1, 10).Select(i => (TextBox)(Controls.Find($"textGame{i}", true)[0]));
Now, simply use a foreach:
foreach(var tb in textBoxes)
{
if (string.IsNullOrWhiteSpace(tb.Text))
{
tb.Text = "EMPTY";
}
}
You can use generic code:
const string baseName = "textBox";
var names = Enumerable.Range(1, 10).Select(x => baseName + x.ToString()).ToList();
var tbxs = names.Select(name => this.Controls.Find(name, true).FirstOrDefault()).Where(x=> x != null).ToList();
foreach (var txt in tbxs) {
if (string.IsNullOrWhiteSpace(txt.Text))
{
txt.Text = "EMPTY";
}
}
You can create your "own" textbox with a placeholder feature:
public class PlaceHolderTextBox : TextBox
{
bool isPlaceHolder = true;
string _placeHolderText;
public string PlaceHolderText {
get { return _placeHolderText; }
set {
_placeHolderText = value;
setPlaceholder();
}
}
//when the control loses focus, the placeholder is shown
private void setPlaceholder()
{
if (string.IsNullOrEmpty(this.Text)) {
this.Text = PlaceHolderText;
this.ForeColor = Color.Gray;
this.Font = new Font(this.Font, FontStyle.Italic);
isPlaceHolder = true;
}
}
//when the control is focused, the placeholder is removed
private void removePlaceHolder()
{
if (isPlaceHolder) {
this.Text = "";
this.ForeColor = System.Drawing.SystemColors.WindowText;
this.Font = new Font(this.Font, FontStyle.Regular);
isPlaceHolder = false;
}
}
public PlaceHolderTextBox()
{
GotFocus += removePlaceHolder;
LostFocus += setPlaceholder;
}
}
Credit for code: https://gntheprogrammer.blogspot.com/2015/03/how-to-add-placeholder-in-windows-forms.html
I just converted it from VB ;)

C#, How to get HTML generated textbox values during foreach Control loop and then show the result?

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.

How to store name of dynamic checkbox in an String array

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

Categories