简体   繁体   中英

Add a row from the checkedlistbox to the DataGridView

I want to add an item to the DataGridView If checked ListBox is checked. but add an item one time.Don't add it twice.

and I want the unchecked object in the checkedlistbox to be deleted as a row in the DataGridView. But my code is not working

我的APP

Video

private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{
    foreach (int indexChecked in checkedListBox3.CheckedIndices)
    {
        if (checkedListBox3.GetItemCheckState(indexChecked) == CheckState.Checked)
        {
            dataGridView3.Rows.Add(checkedListBox3.SelectedItem.ToString());
        }
        else if (checkedListBox3.GetItemCheckState(indexChecked) == CheckState.Unchecked)
        {                    
            dataGridView3.Row[indexChecked].Delete;
        }
    }
}

I would suggest a DerivedCollection . This would work like this:

You have a ReacvtiveList bound to your left panel with checkbox. Person class has to implement INotifyPropertyChanged of course and have Checked property.

Then you can do something like that:

CheckedPeople = People.CreateDerivedCollection(x => x, x => x.Checked);

This will create observable read-only collection storing exactly the same objects that your original list, but filtered by Checked property. Then you can bind CheckedPeople as ItemsSource to your grid and still edit them (only the collection is read only, since it's fed by changes in People collections).

The problem is that each time the checkedListBox event is fired, you loop through all the checked items and add them to the DGV, hence the duplications.

Instead, you can do this:

private void checkedListBox3_SelectedIndexChanged(object sender, ItemCheckEventArgs e)
{

    int selectedIndex = checkedListBox3.SelectedIndex;

    // If item is checked, add it to DGV
    if (checkedListBox3.GetItemCheckState(selectedIndex) == CheckState.Checked)
    {
        dataGridView3.Rows.Add(checkedListBox3.Items[selectedIndex].ToString());
    }

    // If item is unchecked, search for its first occurence in the DGV and remove it
    else if (checkedListBox3.GetItemCheckState(selectedIndex) == CheckState.Unchecked)
    {
        DataGridViewRow row = dataGridView3.Rows
            .Cast<DataGridViewRow>()
            .First(r => r.Cells["ENTER_YOUR_COLUMN_NAME_HERE"].Value.ToString().Equals(checkedListBox3.Items[selectedIndex].ToString()));

        dataGridView3.Rows.Remove(row);

    }
}

I would suggest you toggle ReadOnly property of the GridView depending on the CheckBox value.

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    dataGridView1.ReadOnly = true;
}

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