user5283666
user5283666

Reputation:

Dynamically create checkboxes for each object in list

I have a project for which I want to register which members of a group has attended a meeting on a certain date.

The functionality I want is:

My problem is that I'm stuck trying to create checkboxes dynamically for each object "member" in my List. Is there a smart way to do this?

I figure that I will then loop through each selected checkbox in the group of checkboxes and select the member-id from each member checkbox.checked and pass this to the SQL-query.

All input is welcome as I'm kinda stuck here. :-)

Upvotes: 0

Views: 1914

Answers (2)

user5283666
user5283666

Reputation:

I solved this by using a CheckedListBox like Sidewinder94 suggested, thanks!

First method to fill the checkbox with objects from my people list:

    public void FillCheckBox(List<person> listan)
    {
        checkedListBox1.Items.Clear();
        foreach (person item in listan)
        {
            checkedListBox1.Items.Add(item, true);
        }
    }

I then iterate through all the Checked items and Query my DB with insert for all checked items by using the "checkedListBox1.CheckedItems" collection.

    private void button1_Click(object sender, EventArgs e)
    {
        postgresConnection _con = new postgresConnection();

        group va = (group)comboGrupper.SelectedItem;

        int index = va.gruppid;

        foreach (person item in checkedListBox1.CheckedItems)
            {
                _con.AddPeopleAttendance(item.personid, index);
            }
    }

Thanks for the help! :-)

Upvotes: 2

Maximilian Egger
Maximilian Egger

Reputation: 19

Assuming you are using WPF you could make UserControls for each member of that meeting. If you do so, a simple checkbox inside the UserControl should be enough. If you store the UCs in a List or an Array you can circle through the collection and if the checkbox is checked add it to a secondary List/Array that stores the attendet persons.

public class PersonUC : UserControl
{
   public Person;
   public PersonUC(Person p)
   {
    Person = p;
   }
}

public class MainWindow
{
    private List<PersonUC> personUCs;

    private void MethodCalledAfterEventSelected(List<Person> p)
    {
        //circle through the collection to add the UCs to your listbox
        personUCs = new List<PersonUC>();
        foreach(var item in p)
        {
            personUCs.Add(new PersonUC(item));
        }
        yourListBox.Items = personsUC;
    }

    private List<Person> GetAttendet()
    {
        List<Person> attendet = new List<Person>();
        foreach (PersonUC item in personsUC) 
        {
            if(item.youCheckboxName.Checked)
                attendet.Add(item.Person);
        }
        return attendet;
    }
}

The code is not tested, so there might be a few errors, but i hope i could help.

Upvotes: 0

Related Questions