When I double click on my selected listview item I can easily get each value and set them in a textbox by using the following code.
ListViewItem item = listView1.SelectedItems[0];
entry_txtBox.Text = item.Text;
name_txtBox.Text = item.SubItems[1].Text;
But I'd rather loop through the selected item and compare each column name to each textbox tag. If they match set the column value to the textbox.
This is what I have so far.
foreach (Control c in this.Controls)
{
foreach (Control childc in c.Controls)
{
foreach (ColumnHeader header in listView1.Columns) // This should be the selected item.
{
if (childc is TextBox && header == childc.Tag)
{
// Fill Textboxes
}
}
}
}
Again my question is how can I loop through each column header and compare them to a textbox tag.
First you can use good old recursion to build a flat list of all your controls up by traversing the control tree:
var controls = GetControls(parent);
public IEnumerable<Control> GetControls(Control parent)
{
foreach(var control in parent.Controls)
{
yield return control;
var childControls = GetControls(control);
foreach(var child in childControls)
{
yield return child;
}
}
}
Then just do a LINQ to filter:
var textBoxControls = controls.Select(c => c is TextBox && header == TextBox.ID); //Or whatever condition you want to use.
Related
I am trying to Loop through the tabpages of a tabcontrol in c#. Each tabpage has multiple textboxes. The purpose is to sum up all of the values of these textboxes.
double sum = 0;
foreach(TabPage tbp in tabControl1.TabPages)
{
foreach(System.Windows.Forms.Control c in tbp.Controls)
{
if (c.ToString() == "TextBox")
{
sum += Convert.ToDouble(c.Text);
}
}
}
When I execute this code, the first foreach loop is entered three times even though I have one TabPage in my TabControl. Furthermore, the if statement is not entered, so there seems to be something wrong with that as well.
This code (C#7) allows you to safety sum all text boxes values in a tab control, include text boxes nested in children container controls (example: a text box in panel, and the panel in a tab page)
private double SumTextBoxesValues()
{
double sum = 0;
foreach (TabPage tbp in tabControl1.TabPages)
{
var textBoxes = GetAllTextBoxes(tbp);
foreach (var textBox in textBoxes)
{
if(double.TryParse(textBox.Text, out double value))
sum += value;
}
}
return sum;
}
private static IEnumerable<TextBox> GetAllTextBoxes(Control container)
{
var controlList = new List<TextBox>();
foreach (Control c in container.Controls)
{
controlList.AddRange(GetAllTextBoxes(c));
if(c is TextBox box)
controlList.Add(box);
}
return controlList;
}
I have 2 listviews in tab page. however I am looking for a function to find the right control by name:
I have
foreach (Control c in form.Controls) // loop through form controls
{
if (c is TabControl)
{
TabControl f = (TabControl)c;
foreach (Control tab in f.Controls)
{
TabPage tabPage = (TabPage)tab;
foreach (Control control in tabPage.Controls)
{
MessageBox.Show(control.Name);
// code to go here
}
}
}
}
The Controls collection has a Find function that returns an array:
Control[] ctrls = this.Controls.Find("listView1", true);
if (ctrls.Length == 1) {
MessageBox.Show("Found " + ctrls[0].Name);
}
This will search for a control with the specified name in the controls of the specified control and all his sons.
public Control findControlbyName(String name, Control parent){
foreach (Control ctr in parent.Controls)
{
if (ctr.Name.Equals(name)) return ctr;
else return findControlbyName(name, ctr);
}
return null;
}
You just need to do:
findControlbyName("NameOfTheListView",this);
I have a groupbox in my application which contains child controls.(As seen in the attchached pic). I want to enumerate through all the textboxes for performing some validation using a simple foreach loop.
This document outline would give a fair idea of the housing of the controls
foreach (Control control in grpBxTargetSensitivity.Controls)
{
if (control is FlowLayoutPanel && control.HasChildren)
{
foreach (Control ctrl in control.Controls)
{
if (ctrl is Panel && ctrl.HasChildren)
{
foreach (Control tbox in ctrl.Controls)
{
if (tbox is TextBox)
{
TextBox textbox = tbox as TextBox;
validData &= !string.IsNullOrWhiteSpace(textbox.Text);
}
}
}
}
}
}
My question is, Is there a better way (possibly through LINQ) to get all the controls including the textboxes housed inside the panels than the above method.?
I don't know that this is any better.. whether it's easier to read is a matter of opinion:
var validData
= grpBxTargetSensitivity.Controls.OfType<FlowLayoutPanel>()
.SelectMany(c => c.Controls.OfType<Panel>())
.SelectMany(c => c.Controls.OfType<TextBox>())
.All(textbox => !string.IsNullOrWhiteSpace(textbox.Text));
This'll grab all TextBoxes inside of all Panels in all FlowLayoutPanels in your GroupBox, and return true if all of those TextBoxes have a value in them.
A one liner slution,
IEnumerable<TextBox> collection = grpBxTargetSensitivity.Children.OfType<TextBox>(); //assuming you are looking for TextBox
or
You can try following generic method,
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
then enumerate over the controls as follows,
foreach (TextBox tb in FindVisualChildren<TextBox>(grpBxTargetSensitivity)) //assuming you are looking for TextBox
{
// do something
}
I create one method by the ability to find any controls (or T type) and any inherited object from Control (or T type) for you:
public static List<T> GetSubControlsOf<T>(Control parent) where T : Control
{
var myCtrls = new List<T>();
foreach (Control ctrl in parent.Controls)
{
// if ctrl is type of T
if (ctrl.GetType() == typeof(T) ||
ctrl.GetType().IsInstanceOfType(typeof(T)))
{
myCtrls.Add(ctrl as T);
}
else if (ctrl.HasChildren)
{
var childs = GetSubControlsOf<T>(ctrl);
if (childs.Any())
myCtrls.AddRange(childs);
}
}
return myCtrls;
}
and use that this form for e.g:
foreach (var textbox in GetSubControlsOf<TextBox>(this))
{
validData &= !string.IsNullOrWhiteSpace(textbox.Text);
}
I found following links on StackOverflow itself:
How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
Loop through all the user controls on a page
Give them try. Should work in your case.
I have a C# form with some types of controls, i throught this code for loop all Labels and re-parent:
private void MakeAllLabelTrans(Control frm, Control parent)
{
foreach (Control ctl in frm.Controls)
{
if (ctl is Label)
{
ctl.Parent = parent;
// ctl.BackColor = Color.Transparent;
}
else if (ctl.HasChildren)
{
MakeAllLabelTrans(ctl, parent);
}
}
}
and call as: MakeAllLabelTrans(this, picBackground); in Form_Load event, but some label was missed (i have puted a messagebox in the loop body - it really not in the loop), but i don't know why?
You're changing the collection while enumerating it. This leads to some items being skipped.
You should rewrite this to first build a list of controls that will need to be reparented, and then reparent them in a second pass.
You should not modify the collection on which you are iterating.
private static IEnumerable<Labels> FindAllLabels(Control container)
{
foreach (Control ctl in container.Controls)
{
var lbl = ctl as Label;
if (lbl != null)
{
yield return ctl;
}
else if (ctl.HasChildren)
{
foreach (var innerResult in FindAllLabels(ctl))
yield return innerResult;
}
}
}
// now call the method like this if you want to change a property on the label
foreach (var label in FindAllLabels(theForm))
label.BackgroundColor = Color.White;
// or like this (note the .ToList()) if you want to move the labels around:
foreach (var label in FindAllLabels(theForm).ToList())
label.Parent = someOtherControl;
I have a Repeater control that is creating a dynamic amount of CheckBoxList controls and each list has a different set of ListItems.
I have done this part just fine, but the issue I'm having is how to save the checked states of these dynamically created boxes. I cannot find out how to get the list of these CheckBoxList controls.
Here's some pseudo-code of what I'm trying to do:
foreach (Item i in MyRepeater)
{
if (i.ItemType is CheckBoxList)
{
foreach (ListItem x in i)
{
update table set tiChecked = x.Checked
where table.id = i.id and table.typeid = x.id
}
}
}
I have the ID of the CheckBoxList and the ListItem corresponding to the IDs in the DB.
Edit:
Of course after I ask, I find it out. This seems to be getting me what I want
foreach (RepeaterItem tmp in rptReportList.Items)
{
if (tmp.ItemType == ListItemType.Item)
{
foreach (Control c in tmp.Controls)
{
if (c is CheckBoxList)
{
DisplayMessage(this, c.ID.ToString());
}
}
}
}
You need to look deeper than the RepeaterItem:
// repeater item
foreach (Control cr in MyRepeater.Controls)
{
// controls within repeater item
foreach (Control c in cr.Controls)
{
CheckBoxList chklst = c as CheckBoxList;
if (chklst != null)
{
foreach (ListItem i in chklst.Items)
{
string valueToUpdate = i.Value;
string textToUpdate = i.Text;
bool checkedToUpdate = i.Selected;
// Do update
}
}
}
}