CAD
CAD

Reputation: 4292

Adding , removing items to and from a ListBox after binding

In following button event I'm adding items to a list from another list.

    private void btnAdd_Click(object sender, EventArgs e)
    {
        if (lstPermissions.SelectedItem != null)
        if (!lstGivenPermissions.Items.Contains(lstPermissions.SelectedItem))
        {
            lstGivenPermissions.Items.Add(lstPermissions.SelectedItem);
        }
    }

When the Items were hard coded in lstPermissions and lstGivenPermissions's datasource is not set , it was fine. But After binding data to lstGivenPermissions, when I try to execute this method I'm getting this exception.

Items collection cannot be modified when the DataSource property is set.

I'm using this property to bind data to the lstGivenPermissions

    public List<string>  GivenPermission
    {
        get { return lstGivenPermissions.Items.Cast<string>().ToList(); }
        set { lstGivenPermissions.DataSource = value; }
    }

I can understand that the databinding has caused this exception. But my requirement is that I want to load all permissions to lstPermissions and selected user's permissions to lstGivenPermission from the database. Then I should be able to add and remove items to and from lstGivenPermissions. Could you let me know how to do this?

Upvotes: 0

Views: 1134

Answers (1)

bastos.sergio
bastos.sergio

Reputation: 6764

You shouldn't be using a property to bind to a list control... Properties should just save/load values, like so:

private List<string> _givenPermission;
public List<string>  GivenPermission
{
    get { return _givenPermission; }
    set { _givenPermission = value;}
}

If you must bind, try doing it this way instead:

private List<string> _givenPermission;
public List<string>  GivenPermission
{
    get { return _givenPermission; }
    set { _givenPermission = value; lstGivenPermissions.DataSource = value; }
}

Upvotes: 2

Related Questions