Is it possible to turn a button into a variable? - c#

I have a code in C# with 26 button in it and I want them to all be disabled until the user does something, but I dont want to copy/paste button1.Enable = false; Button2.Enable = false...
So is there a way to do something like this :
for (int i = 1; i < 26; i++)
{
button+i.Enable = false;
}
Thanks for your help.

You probably want to iterate buttons directly.
foreach(var button in this.Controls.OfType<Button>())
{
button.Enable = false;
}

Using either of Controls.Find or Controls.OfType<Button>() only works at run-time. I prefer a statically checkable compile-time approach. Then if you delete a button on the form the code won't compile. Helps give you that type-safe feeling.
I do it this way. Start with a field to hold the buttons in an array:
private Button[] _buttons = null;
Set the array once in your initialization code:
_buttons = new[] { button1, button2, button26 };
Then when you need to do something with the buttons you just do this:
foreach (var button in _buttons)
{
button.Enable = false;
}

You can use Form.Controls.Find()
for (int i = 1; i < 26; i++)
{
this.Controls.Find("button" + i, searchAllChildren: false).Enable = false;
}
The code assumes your buttons are named button1 through button26.
It's not possible directly like you are, but that doesn't make sense anyway.

Related

How to change opacity of certain number of button(x) while not writing them out one by one? (C#)

I don't think I asked the question quite well, so here's an explanation. I want to create buttons invisibly when Form1 loads, instead of changing them each individually, is there a way to change all of them with fewer lines of code?
Note: I do not want to change all buttons, only a certain range of them.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Visible = true;
button2.Visible = true;
button3.Visible = true;
button4.Visible = true;
button5.Visible = true;
button6.Visible = true;
button7.Visible = true;
}
By that I mean, is it possible to change those buttons visibility to true without writing them out one by one?
button1 - button7.Visible = true;
something like this..
If you're trying to change only a certain range of buttons, assuming they're all simply called button[x] you could create a function like this:
private void toggleButtons(int start, int end, bool trueOrFalse)
{
for(int x=start; x <= end; x++)
{
this.Controls.OfType<Button>().Where(b => b.Name == "button" + x.ToString()).SingleOrDefault().Visible = trueOrFalse;
}
}
Then you can call it like this using (startNo,endNo,true/false for visibility)
toggleButtons(1, 7, false);
You can use the Controls property to get all of the controls on a form. For example:
foreach(var button in this.Controls.OfType<Button>())
{
button.Visible = false;
}
If you want to change visibility of all buttons in the form, you could do so.
foreach(var button in Controls.OfType<Button>())
{
button.Visible = false; // or true, depending what you want to set
}
If you do no want to change visibility of all Buttons in Form and if you need to filter buttons, based on some criteria, you could do so as well.
For example, if you want to filter buttons whose names starts with "specialButton",
foreach(var button in this.Controls.OfType<Button>().Where(x=>x.Name.StartsWith("specialButton")))
{
button.Visible = false;
}
Similarly, you can filter based on other properties as well.
Another option is to enlist the buttons that needs to be changed in a list. For example, if you need to change only button1 and button2 from a form comprising of 10 buttons, you could
var list = new[] { button1, button2 };
foreach (var item in list)
{
item.Visible = false;
}

How to reference a ListBox name using a string in Csharp

for (int i=1; i<4; i++)
{
string buttonName = "button" + i;
if (Controls[buttonName].BackColor = Color.Red)
{
Controls[buttonName].Enabled = false;
}
}
This code works perfectly. The code checks 3 different buttons (button1, button2, button3) and if their color is red they become disabled. The button name is referenced using a string:
Controls[buttonName]
Is there a way to reference a ListBox using a string in the same way? What would "Controls" need to be changed to?
If you simply want to go over all ListBoxes, you could also use .OfType<T>()
foreach (ListBox lb in this.Controls.OfType<ListBox>())
{
lb.Enabled = false;
}
... and it would of course work the same for .OfType<Button>() without the need to name your controls in a way to enumerate them.

Changing The Property Of An Object Using Variables? C#/Visual Studio

Ok so I have 100 buttons and I need to change there colors based on conditions in a while loop. They are named button1, button2, button3 ,etc. during the first time around the loop (iteration?) I need to edit button1, the next time button2 the third time button3, etc.
I thought I could just make a string that equaled "button", add the number of times around the loop to it and change the color like that.
String ButtonNumber = "button" + i; where i = number of times around loop
When I try to edit the color using ButtonNumber.BackColor = Color.Red; it won't let me because it's not treating ButtonNumber like a button, but like a string. How do I accomplish this? Thanks! (this is my first time programing pretty much)
Consider using Controls.Find to find a control by name, and then you can change it's properties:
for (int i = 1; i <= 100; i++)
{
var buttonName = string.Format("button{0}", i);
var foundControl = Controls.Find(buttonName, true).FirstOrDefault();
if (foundControl != null)
{
// You can now set any common control property using the found control
foundControl.BackColor = Color.Red;
// If you need to set button-specific properties (i.e. properties
// that are not common to all controls), then cast it to a button:
var buttonControl = foundControl as Button;
if (buttonControl != null)
{
buttonControl.AutoEllipsis = true;
}
}
}

CheckBox state is not updated after click in C# WinForms

I have a list of CheckBoxes and after clicking on them the state is not updated.
Why is this happening and how can I repair this?
private List<CheckBox> blocks_check_boxes = new List<CheckBox>();
count = blocks_from_database.Count;
/* Display check boxes for each block*/
for (int i = 0; i < blocks_from_database.Count; i++)
{
blocks_check_boxes.Add(new CheckBox());
this.blocks_check_boxes[i].AutoSize = true;
this.blocks_check_boxes[i].Name = blocks_from_database[i].name;
this.blocks_check_boxes[i].Size = new System.Drawing.Size(80, 17);
this.blocks_check_boxes[i].TabIndex = 3 + i;
this.blocks_check_boxes[i].Text = blocks_from_database[i].name;
this.blocks_check_boxes[i].UseVisualStyleBackColor = true;
this.blocks_check_boxes[i].AutoCheck = true;
}
Thank you
Maybe you are recreating the CheckBoxes in an unwanted way.
Maybe you want to set the "AutoPostBack" property till "true".
It's pretty hard to understand what's causing your problem when we don't see more code. Explain a little more when you are detecting your problem and also where and when your code above is executing.

Changing button properties in a loop, for example

I would like to know how it's possible to change button properties by a code when we don't know a button name while writing it.
For example, I have a loop like this:
for (int i=0; i<5; ++i) {
int buttonName = "button_" + i;
buttonName.enabled = false;
}
Thanks in advance!
You can access the Controls collection of the parent containing the button like this:
if(parent.Controls.ContainsKey(buttonName))
{
Button myButton = (Button)parent.Controls[buttonName];
myButton.Enabled = false;
}
This will need a little extra work if your buttons are not contained within the same parent; ie. some buttons on a Form, some buttons on a Panel contained within that same form.

Categories