dbso
dbso

Reputation: 696

C# dynamic radiobuttons, change text

I have a function that creates X amounts of radio buttons every time a user clicks a button. Code looks like this now (I've also tried grouping them). Now I just use the simplest method I could think of.

private void createRadioButtons(int amount, String answ)
{
   String[] splitAnsw = answ.Split(new Char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // Splits up a string containing the radio button text

   for (int i = 0; i < amount; i++) {
        RadioButton rb = new RadioButton();
        rb.Text = splitAnsw[i];
        rb.Location = new Point(200, 300 + i * 20);
        this.Controls.Add(rb);
        Console.WriteLine(splitAnsw[i]);
    }
}

This does indeed create X of them, but the problem comes when the text should be updated. The text in splitAnsw does change and displays correctly when writing them out, but the text in radio buttons will not be updated.

Upvotes: 0

Views: 559

Answers (1)

RePierre
RePierre

Reputation: 9566

You are creating quite a lot of controls there and this will lead to bad performance. You need to cleanup your code a little bit.

First of all, declare a private member in your class to hold references to your newly created controls.

private IEnumerable<Control> _controls = null;

Create a method to remove the old controls:

private void ClearOldControls()
{
    if(_controls != null)
    {
        foreach(var control in _controls)
        {
            this.Controls.Remove(control);
            control.Dispose();
        }
    }
}

Now, in your method, before creating new controls remove the old ones:

private void createRadioButtons(int amount, String answ)
{
    ClearOldControls();
    // Create new ones
    _controls = answ.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries)
        .Take(amount)
        .Select(answer =>
        {
            var rb = new RadioButton();
            rb.Text = answer;
            this.Controls.Add(rb);
            return rb;
        });
}

Of course, don't forget to call Control.SuspendLayout() before inserting/removing controls into the container and Control.ResumeLayout() after you've finished.

Upvotes: 1

Related Questions