2

There is string array contains some file location.

I am using a foreach loop, in which each loop i want to create a new radio button control. without foreach code performs, but in loop only one control is adding.

Can anybody tell me why? and how I perform this.

Code:

string[] location =
{
    @"C:\Program Files\Skype\Phone\Skype.exe",
    @"C:\Program Files\iTunes\iTunes.exe",
    @"C:\Program Files\Internet Explorer\iexplore.exe"
};

int i = 10;
foreach (string path in location)
{
    if (File.Exists(path))
    {
        RadioButton rbList = new RadioButton();
        rbList.AutoSize = false;
        Icon icn;
        icn = Icon.ExtractAssociatedIcon(path);
        rbList.Image = icn.ToBitmap();
        rbList.Height = 100;
        rbList.Width = 50;
        i = i + 30;
        rbList.Location = new Point(100, i);

        groupBox1.Controls.Add(rbList);
    }
}
1

4 Answers 4

2

You set the height to 100 but increase the position by 30 only.

rbList.Height = 100; 
...
i = i + 30;
rbList.Location = new Point(100, i);

You can decrease the height below 30:

rbList.Height = 30; //or smaller

or

increase the "i" more than 100:

i = i + 100; //or more than 100
rbList.Location = new Point(100, i);
Sign up to request clarification or add additional context in comments.

1 Comment

thanx buddy, I got my fault. I need to improve my maths
0

Add

rbList.AutoSize = true;

And be sure your groupBox1 is large enough to display all your radio buttons.

Comments

0

Little bit of changes:

i = i + 100;
rbList.Location = new Point(100, i);

groupBox1.Controls.Add(rbList);

int space = 10;
groupBox1.Height += rbList.Height + space;

This work without alignment, alignment is yours.

Comments

0
int i = 10;
var radios = new[] { "", "", "" }
    .Where(path => File.Exists(path))
    .Select(path => new RadioButton
        {
            AutoSize = false,
            Image = Icon.ExtractAssociatedIcon(path).ToBitmap(),
            Height = 100,
            Width = 50,
            Location = new Point(100, (i = i + 30))
        })
     .ToArray();

groupBox1.Controls.AddRange(radios);

2 Comments

Thanx... but in my case number of radio Buttons depends on the no of given paths. What if user gives more paths i.e. dynamically any number of RB could be used.
@Pawan: Then use not an explicitly declared array but an array passed as a parameter - returned by the user

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.