Search code examples
c#winformsvisual-studiocheckedlistbox

Add dynamic labels and textboxes from a checkedListBox


I have a checkedListBox, that contains names of some chargingstations i have in a SQL database. I have filled the checkedListBox with the station names, and i would like that if you check an item in the box, a label with the text "Km to "+itemsChecked.StationName would appear just below the checkedListbox, as well as a textBox, where one would enter the kilometers to the station. It's being used to create a new charging station, and the kilometers are the cost of the edge to the next station. I've tried something like this:

private void stationCheckedListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (BetterServiceReference.Station itemsChecked in stationCheckedListBox.CheckedItems)
        {
            var lbl = new Label();
            lbl.Name = "lblAuto" + itemsChecked.StationId;
            lbl.Text = "Km to " + itemsChecked.StationName;
            lbl.AutoSize = true;
            lbl.Location = new Point(33, 462);
            lbl.Name = "label1";
            lbl.Size = new Size(35, 13);
            tabPage7.Controls.Add(lbl);
        }

Only it doesn't actually create a label.


Solution

  • I created a sample program, and it seems to work fine for me:

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                foreach (var item in checkedListBox1.CheckedItems)
                {
                    Label lbl = new Label();
                    lbl.Text = "Testing";
                    lbl.Location = new Point(125, 125);
                    this.Controls.Add(lbl);
                }
            }
        }
    

    Some things to check / try:

    • Make sure the location of your label is not behind some other control!!
    • Use var / object instead of "BetterServiceReference.Station"
    • Is tabPage7 the name of your form? Try using this.Controls.Add(lbl);

    I will also warn you that your function will not remove the labels once an item is unchecked. Also, as-is, it will only create one label in one spot for any checkbox checked. It's going to take a bit of work to implement what you are trying to do; as the other answer suggested, you may be better off toggling controls between visible / invisible.

    But, hopefully my answer will help you dynamically create a label, and creating the textboxes will be very similar.