views:

36

answers:

3

I am trying to give names to my dynamically generated checkboxes through a for loop an algorithm. Coming up with the algorithm was pretty simple but I am unable to give them name/checkbox text. The best I could come up with was a similar checkbox text for everything that was generated. Is there a way to name them?

Below is the code I came up with

int x = ((((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
    Label1.Text = x+"";
    for (int i = 0; i < x; i++)
    {
        CheckBox cb = new CheckBox();
        cb.Text = "1 & 2";
        PlaceHolder1.Controls.Add(cb);
        PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
    }

Any help is greatly appreciated.

Cheers, Jaf

A: 

You should assign the name using the control's ID property.

Like this:

for (int i = 0; i < x; i++)
{
    CheckBox cb = new CheckBox();

    cb.ID = "checkBox" + i;

    PlaceHolder1.Controls.Add(cb);

    PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}

The Text property can be equal in every control.
You can't have identical names (IDs) for controls.

Leniel Macaferi
A: 

You can use index of for statement:

int x = ((((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
    Label1.Text = x+"";
    for (int i = 0; i < x; i++)
    {
        CheckBox cb = new CheckBox();
        cb.Text = String.Format("PrefixName{0}" , Convert.ToString(i+1));
        PlaceHolder1.Controls.Add(cb);
        PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
    }
DEVMBM
A: 

Look at this links

I think Leniel is right you cant have identical names.

Rye