Hello Everybody
How can store name of dynamically created checkbox in a String array when I don't know how many checkbox will user select at runtime.
Say I have 10 dynamic checkboxes and out of 10 user select 6 checkboxes randomly now how can get the name of those selected checkboxes and store them in a String array.

I know how to use event handler on dynamic check box but confused how to declare Straing array when I don't know what will be be size of an array.

Here what I have done till now -

        private void CheckBoxCheckedChanged(object sender, EventArgs e)
        {
            CheckBox c = (CheckBox)sender;
            //Label myLabel;
            String str = null;
            if (c.Checked == true)
            {
                str = c.Text;
                gpBox[gpcount] = new GroupBox();
                gpBox[gpcount].Name = "gpBox" + Convert.ToString(count);
                gpBox[gpcount].Text = str;
                gpBox[gpcount].Location = new Point(5, gpposition);
                gpBox[gpcount].AutoSize = true;
                this.Controls.Add(gpBox[gpcount]);

                aCommand3 = new OleDbCommand("select * from batch_tbl where batch_branch LIKE '" + str + "'", main_connection);
                aAdapter3 = new OleDbDataAdapter(aCommand3);
                ds3 = new DataSet();
                aAdapter3.Fill(ds3, "app_info");
                ds3.Tables[0].Constraints.Add("pk_bno", ds3.Tables[0].Columns[0], true);
                int batch_count = ds3.Tables[0].Rows.Count;
                batchCheckBox = new CheckBox[batch_count];
                //filling the groupbox with batch code by generating dynamic checkboxes
                for (int j=0; j < batch_count; ++j)
                {
                    batchCheckBox[j] = new CheckBox();
                    batchCheckBox[j].Name = "batch" + Convert.ToString(k);
                    batchCheckBox[j].Text = ds3.Tables[0].Rows[j][1].ToString();
                    Console.WriteLine(batchCheckBox[j].Text);
                    batchCheckBox[j].Location = new System.Drawing.Point(104 * position, 30);
                    gpBox[gpcount].Controls.Add(batchCheckBox[j]);
                    batchCheckBox[j].CheckStateChanged += new System.EventHandler(BatchBoxCheckedChanged);
                    position++;
                    count++;
                    Console.WriteLine(batchCheckBox[j].Name);
                    k++;
                }
                position = 1;
                gpposition += 100;
            }
            else
            {
                count--;
                this.Controls.RemoveByKey("lbl" + c.Name);
                this.Update();
            }
        }
        int total_batch = 1;
        string[] batchname;
        private void BatchBoxCheckedChanged(object sender, EventArgs e)
        {
            CheckBox batchBox = (CheckBox)sender;
            //Here I want to store name of checkbox in array
            if (batchBox.Checked == true)
            {
                batchname = new String[total_batch];
                total_batch++;

            }
            else
            {
            }
        }

Dani AI

Generated

A concise, reliable strategy is to avoid fixed arrays and either (A) maintain a single class-level collection that is updated when a checkbox changes or (B) take an on-demand snapshot of checked boxes with LINQ. Both approaches solve the "unknown count at runtime" problem mentioned by and follow the direction suggested by and .

Keep a single collection (initialized once) and update it in the CheckedChanged handler. A HashSet gives uniqueness and fast add/remove; List preserves order when needed. Store a stable identifier (database id) in Tag when creating each checkbox so the selection key does not depend on display text:

private readonly HashSet<string> selectedKeys = new HashSet<string>();

private void BatchCheckBox_CheckedChanged(object sender, EventArgs e)
{
    var cb = (CheckBox)sender;
    var key = cb.Tag?.ToString() ?? cb.Name;
    if (cb.Checked) selectedKeys.Add(key);
    else selectedKeys.Remove(key);
}

If a snapshot is preferred (no incremental state), enumerate the relevant controls and materialize the result when needed. For nested groupboxes (as in the OP's layout) this captures all batch checkboxes:

var picked = this.Controls.OfType<GroupBox>()
    .SelectMany(g => g.Controls.OfType<CheckBox>())
    .Where(cb => cb.Checked)
    .Select(cb => cb.Text)
    .ToList();

Notes and pitfalls: call ToList() or ToArray() when a concrete collection type is required (that fixes the IEnumerable-to-List error shown earlier). Do not reinitialize the collection inside the CheckedChanged handler. For WinForms the dynamic controls persist at runtime; for ASP.NET WebForms dynamic controls must be recreated early in the page lifecycle (Page_Init) to preserve events. Prefer using a stable id in Tag instead of Text for storage and comparisons.

Recommended Answers

All 4 Replies

Don't store them in a string array, use a List<string> type instead.

You could even go one step further and use a List<GroupBox>.

Thank you DDANBE and Tinstaff
I am trying that only but not finding the correct way of implementing the code for list
See what I have done and what messup I have done

    // Added this line in class level
    List<CheckBox> chks;
    // Added this line inside constructor
    chks = Controls.OfType<CheckBox>().ToList();
    int total_batch = 1;
        private void BatchBoxCheckedChanged(object sender, EventArgs e)
        {
            CheckBox batchBox = (CheckBox)sender;
            //Here I want to store name of checkbox in array
            List<string> names = chks.Where(batchCheckBox => batchCheckBox.Checked).Select(batchCheckBox => batchCheckBox.Name);

            if (batchBox.Checked == true)
            {       
                total_batch++;
            }
            else
            {
            }
        }

But getting this error

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to 'System.Collections.Generic.List<string>'. An explicit conversion exists (are you missing a cast?) D:\TimeTable\TimeTable\main.cs 138 34 TimeTable

     }
            list = new List<string>();
        }

        private void BatchBoxCheckedChanged(object sender, EventArgs e)
        {
            CheckBox batchBox = (CheckBox)sender;
            //Here I want to store name of checkbox in array

            if (batchBox.Checked == true)
            {
                list.Add(batchBox.Text);  
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            foreach(string prime in list) // Loop through List with foreach
            {
                Console.WriteLine(prime);
            }
        }       

Done

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.