HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Converting string to control

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertingstringcontrol

Problem

I have an up-down numeric control on my form (attEdgeUpDown), which has value 0-8. I have eight checkboxes (attEdgeBox1 to attEdgeBox8). I want to display as many boxes as the numeric control shows.

Can this be done more efficiently?

private void attEdgeUpDown_ValueChanged(object sender, EventArgs e)
{
int edgeValue = Convert.ToInt32(attEdgeUpDown.Value);
    for (int i = 1; i <= 8; i++)
    {
    string checkboxName = "attEdgeBox" + Convert.ToString(i);
    Control[] checkboxControl = this.Controls.Find(checkboxName, true);
        if (i <= edgeValue)
            {
                (checkboxControl[0] as CheckBox).Visible = true;
            }
            else
            {
                (checkboxControl[0] as CheckBox).Visible = false;
                (checkboxControl[0] as CheckBox).Checked = false;
            } 
    }
}

Solution

Unless you're working with an ancient version of .NET, Convert.ToString(i); is superfluous. You should be able to just do "attEdgeBox" + i;.

If you're certain that those checkboxes exist, you can do var checkBox = this.Controls.Find(checkboxName, true).FirstOrDefault() as CheckBox; and then work with checkBox instead of doing (checkboxControl[0] as CheckBox) repeatedly.

Note that CheckBox is a compound name, so checkboxName as a variable name is incorrect; it should be checkBoxName.

What type is attEdgeUpDown, and why does it return a value that isn't an int? Seems odd to me that a control that returns a value from 1 to 8 would return this in a non-numeric format.

Context

StackExchange Code Review Q#134530, answer score: 10

Revisions (0)

No revisions yet.