I'm trying to reverse the order of Controls in a FlowLayoutPanel.
I tried converting the ControlCollection to an array and then reversed that and cleared the ControlCollection and then readded the Controls. But this doesn't seem to have the planned effect.
Here's the code I use:
private static void ReverseLayout(Control control, bool suspend = true) {
if (suspend) control.SuspendLayout();
Control[] newCC = new Control[control.Controls.Count];
control.Controls.CopyTo(newCC, 0);
Array.Reverse(newCC);
control.Controls.Clear();
//control.Controls.AddRange(newCC);
for (int i = 0; i < newCC.Length; i++) {
newCC[i].Location = new System.Drawing.Point(); // maybe? no :\
newCC[i].TabIndex = i; // maybe? no :\
control.Controls.Add(newCC[i]);
}
if (suspend) control.ResumeLayout(false);
}
Your code seems more complicated than it needs to be. Try putting the controls in a List<Control> and then call reverse on it, put the collection back:
int firstTabIndex = flp.Controls[0].TabIndex;
List<Control> controls = flp.Controls.Cast<Control>().ToList();
flp.Controls.Clear();
controls.Reverse();
flp.Controls.AddRange(controls.ToArray());
For the TabIndex property, you would have to reapply the value:
for (int i = 0; i < flp.Controls.Count; ++i) {
flp.Controls[i].TabIndex = firstTabIndex + i;
}
Related
I want to create labels that will follow one another. I have a grid name WordTemplateLayout to which I want to add the labels. I add them dynamically on the wpf window constructor after InitializeComponent() is called. Here is the method creating the labels:
private void CreateWordTemplate()
{
IList<char> template = CurrentGame.Template;
double widthPerBox = WordTemplateLayout.Width / template.Count;
//template.Count being a number, irrelevant to the question
for (int i = 0; i < template.Count; i++)
{
var templateVisual = new Label();
templateVisual.Name = "c" + i;
templateVisual.Width = widthPerBox;
templateVisual.Height = WordTemplateLayout.Height;
templateVisual.Background = new SolidColorBrush(Colors.Aqua);
WordTemplateLayout.Children.Add(templateVisual);
}
}
the problem being, that what actually appends is that instead of the labels lining up one after the other, they overlap each other:
The aqua box is all the labels overlap each other
so what I am asking, is how can I make the labels line up (horizontally) instead of to overlap?
As others have pointed out, you're better off using a StackPanel, or learning how to use viewmodels and data binding. Having said that, to answer your direct question, here's how you'd do it programmatically.
**NOTE: Ignore the 5 that I'm passing in to the methods, and instead use your template.Count. This is was just for me to get it to work on my end.
public MainWindow()
{
InitializeComponent();
CreateGridLayout(5);
CreateWordTemplate(5);
}
// Define the Grid layout
// If you want the labels to follow one another horizontally, define columns.
// If you want them stacked vertically, instead define rows.
private void CreateGridLayout(int count)
{
for (int i = 0; i < count; i++)
{
WordTemplateLayout.ColumnDefinitions.Add(new ColumnDefinition());
}
}
private void CreateWordTemplate(int count)
{
double widthPerBox = WordTemplateLayout.Width / 5;
for (int i = 0; i < 5; i++)
{
var templateVisual = new Label();
templateVisual.SetValue(Grid.ColumnProperty, i); // SET YOUR COLUMN HERE!
templateVisual.Name = "c" + i;
templateVisual.Width = widthPerBox;
templateVisual.Height = WordTemplateLayout.Height;
templateVisual.Background = new SolidColorBrush(Colors.Aqua);
templateVisual.Content = templateVisual.Name;
WordTemplateLayout.Children.Add(templateVisual);
}
}
you need to use another layout so the new elements will get in normal order. try stackPanel.
you can use grid and give each new label Row=index.
you can give each new label margin, like newLabel.margin-top = index*50
I want to set up a for loop to change the content of pictureboxes with using like picturebox[i] but I can't figure out how to do that.
My idea was doing something like this, the whole code snippet has a lot of if statements but is similar to this.
for (int i = 0; i < length; i++)
{
pictureBox[i].image = Image.FromFile("../Pics/Salmon.jpg");
}
I don't know how to do it and I cant' find anyone with the same problem. Is there any way how to do this? Or do I have to manually do it.
You can prepare collection first and then iterate it:
var pictureBox = new[] { pictureBox1, pictureBox2, ... };
for (int i = 0; i < pictureBox.Length; i++)
pictureBox[i].Image = Image.FromFile("../Pics/Salmon.jpg");
You can use same approach to have different pictures, I'll let it for you as a kind of exercise ;)
You can't access the PictureBox controls in an array. They are part of the overall control collection on a form. You can loop through all the controls on a form and only act on the picture boxes.
Example:
foreach (Control ctrl in this.Controls)
{
if (ctrl is PictureBox picBox) //determine if the control is a picture box
{
picBox.Image = Image.FromFile("../Pics/Salmon.jpg");
}
}
Or using Linq:
this.Controls.OfType<PictureBox>().ToList()
.ForEach(p => p.Image = Image.FromFile("../Pics/Salmon.jpg"));
Or if you have to act on based on posistion array:
var pics = this.Controls.OfType<PictureBox>().ToArray();
for (int i = 0; i < pics.Length; i++)
{
pics[i].Image = Image.FromFile("../Pics/Salmon.jpg");
}
Is it possible to set a components visible attribute based on its name?
I have 12 "master" components (comboboxes) if you want to call them that and based on the selection in these I want to display anywhere from 1 to 16 textboxes. These are named in numeric order such as combobox1_textbox_0, combobox1_textbox_1 and so on. What I would like to do ideally is take the index of the combobox and pass it as a parameter to a method that sets the textboxes visible attribute to visible/hidden depending on the index passed into the method.
Is this possible? in pseudocode or what you call it I would like it to work something like this:
private void methodToSetVisibleAttribute(int indexFromMainComboBox)
{
for(int i = 0; i < 15; i++)
{
if(i < index)
{
combobox1_textbox_+i.Visible = true;
}
else
{
combobox1_textbox_+i.Visible = false;
}
}
}
I could do panels or something for the choices but seeing as all the selections from the combobox will use the same textboxes but in different amounts it seems like alot of work to make a panel for every possible selection not to mention difficult to expand the program later on.
Assuming you are using Windows Forms and not WPF, you can use ControlCollection.Find() to find controls by name:
var textBox = this.Controls.Find(string.Format("combobox1_textbox_{0}", i), true).OfType<ComboBox>().FirstOrDefault();
if (textBox != null)
textBox.Visible = (i < index);
else
Debug.Assert(false, "textbox not found"); // Or throw an exception if you prefer.
I'll suggest an alternative to your approach, maybe not quite what you're looking for:
Place your combo boxes in a List<ComboBox> and you can access them by an index number.
List<ComboBox> myCombos = new List<ComboBox>();
for (int i = 0; i < 16; i++)
{
ComboBox cb = new ComboBox();
//do what ever you need to do here. Set its location, add items, etc.
Form1.Controls.Add(cb); //Alternatively add it to another container.
myCombos.Add(cb); //Now it's in a list.
}
Modify them like this:
for(int i = 0; i < 15; i++)
{
if(i < index)
{
myCombos[i].Visible = true;
}
else
{
myCombos[i].Visible = false;
}
}
Or even more succintly:
for(int i = 0; i < 15; i++)
{
myCombos[i].Visible = i < index;
}
I have the WinForm, there I have a lot of controls, and on certain moments I need to change the properties for some of them.. so, I create the Control array and determines what should be changed
controls = new Control[] {loadFromFile_btn, logout_btn, postBtn, waitFrom_tb, waitTo_tb, messageTB, recurs_check};
ChangeStatus.activStatus(controls);
Then in my class ChangeStatus make changes to all of these elements are in an array
public static void activStatus(Control[] controlObj)
{
for (int i = 0; i < controlObj.Count() - 1; i++)
{
controlObj[i].BeginInvoke((Action)delegate
{
if (controlObj[i] is TextBox || controlObj[i] is CheckBox || controlObj[i] is Panel)
controlObj[i].Enabled = true;
else
{
controlObj[i].BackColor = Color.DarkGray;
controlObj[i].Enabled = true;
}
});
}
}
But I have a problem... the change applies only to the last element in the array. Help me please..
That's because of the closure.Try storing i in a local variable and use it in your anonymous method
for (int i = 0; i < controlObj.Count() - 1; i++)
{
int j = i;
controlObj[i].BeginInvoke((Action)delegate
{
if (controlObj[j] is TextBox || controlObj[j] is CheckBox || controlObj[j] is Panel)
controlObj[j].Enabled = true;
else
{
controlObj[j].BackColor = Color.DarkGray;
controlObj[j].Enabled = true;
}
});
}
I have ten labels on a page. I want to make these invisible in a for loop on page load.
I have tried this (doesn't work):
for (int i = 0; i < 10; i++)
{
my_lbl+i.Visible = false;
}
Therefore, it should do:
my_lbl1.Visible = false;
my_lbl2.Visible = false;
my_lbl3.Visible = false;
my_lbl4.Visible = false;
etc...
Is there a way to do this?
Put all of the labels into a collection:
private List<Label> labels = new List<Label>{my_lbl1, my_lbl2, my_lbl3, my_lbl4};
Then you can iterate the whole collection:
foreach(var label in labels)
label.Visible = false;
Make a List of them;
List<Label> yourlabels = new List<Label>{my_lbl1, my_lbl2, my_lbl3...};
and use foreach loop making them visible.
foreach(var label in yourlabels)
{
label.Visible = false;
}
I don't know if there is a better way but this way seems logical to me.
Putting the labels in a collection (as the previous answers have suggested) is a great solution. You can also retrieve the controls by their name using FindControl method of the Page.
for (int i = 0; i < 10; i++)
{
this.FindControl("my_lbl" + i.ToString()).Visible = false;
}
I guess you can utillize Page's FindControl method:
for (int i = 0; i < 10; i++)
{
FindControl(string.Format("my_lbl{0}", i)).Visible = false;
}
But check the case if control is not found of course.
Or, you can put them into dictionary:
Dictionary<string, Label> nameOfDict = new Dictionary<string, Label>();
nameOfDict.Add("label1", label1);
nameOfDict.Add("label2", label2);
For...
nameOfDict ["label" + incrementator].visible = false;
Or, create them dynamically into an array of labels.
If you're sure that, let's say, you want to uncheck all checkboxes in a groupbox, you can do this, too:
foreach (var item in groupBox1.Controls)
{
if (item.GetType() == typeof(CheckBox))
{
((CheckBox)item).Checked = true;
}
}
with LINQ:
foreach (var item in groupBox1.Controls.Cast<object>().Where(item => item.GetType() == typeof(CheckBox)))
{
((CheckBox)item).Checked = true;
}