简体   繁体   中英

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?

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM