locked
remove item from cheklistbox RRS feed

  • Question

  • How to Remove Checked item from Bound checkedListBox..

    label2.Text = checkedListBox1.GetItemText(checkedListBox1.SelectedItem);
                label6.Text = checkedListBox2.GetItemText(checkedListBox2.SelectedItem);
                SqlConnection con = new SqlConnection("Data Source=mtdev02; Initial Catalog = " + comboBox1.Text + "; User ID=sa;Password=123456");
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "insert into grid_store(src_table,dest_table) Values (@src,@dest)";
                cmd.Parameters.AddWithValue("@src", label2.Text);
                cmd.Parameters.AddWithValue("@dest", label6.Text);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                foreach (var item in checkedListBox1.CheckedItems)
                {
                    checkedListBox1.Items.Remove(item);
                }

    Friday, September 23, 2016 4:37 AM

Answers

  • Hello,

    The following was put together from a MSDN code sample I did a while back.

    Full source for the code below is on OneDrive.

    Here a class is used to remember information about a Checked item and is used in a lambda statement in code block 2.

    public class CheckedData
    {
        /// <summary>
        /// Associated data row for the checked item
        /// </summary>
        public DataRow Row { get; set; }
        /// <summary>
        /// Item index in the CheckedListBox
        /// </summary>
        public int Index { get; set; }
        /// <summary>
        /// Primary key for Row property
        /// </summary>
        public int Identifier { get; set; }
    }

    Here is a language extension method so we keep this code out of where you would implement it e.g. in a form.

    public static List<CheckedData> IndexList(this CheckedListBox sender)
    {
        return
            (
                from item in sender.Items.Cast<DataRowView>()
                    .Select(
                    (data, index) =>
                        new CheckedData
                        {
                            Row = data.Row,
                            Index = index,
                            Identifier = data.Row.Field<int>("Identifier")
                        }
                    )
                    .Where((x) => sender.GetItemChecked(x.Index))
                select item
            ).ToList();
    }

    Simple demo where I load mocked data that would represent data returned from a database table. The mocked data is set to a CheckListBox.

    ViewDataButton: Shows currently checked items.

    removeChrrentButton: Remove current checked item.

    removeAllRows: clears all DataRow(s) from the source.

    Now what you are looking for, removed checked items and return the primary key which here is mocked but if the data came from a table in a database this provides the key to do work in the database table. 

    using System;
    using System.Data;
    using System.Windows.Forms;
    
    namespace CheckListBoxSimple_C_Sharp_1
    {
        public partial class Form1 : Form
        {
            public Form1()   { InitializeComponent(); }
    
            // Used to simulate data coming from a database table
            DataTable dtMocked = new DataTable();
    
            void Form1_Load(object sender, EventArgs e)
            {
                dtMocked.Columns.Add(new DataColumn
                {
                    ColumnName = "Identifier",
                    DataType = typeof(Int32),
                    AutoIncrement = true,
                    AutoIncrementSeed = 2,
                    AutoIncrementStep = 10
                });
    
                dtMocked.Columns.Add(new DataColumn { ColumnName = "ItemName",
                    DataType = typeof(string) });
                dtMocked.Columns.Add(new DataColumn { ColumnName = "ExtraData",
                    DataType = typeof(string) });
    
                dtMocked.Rows.Add(new object[] { null, "One", "Extra 1" });
                dtMocked.Rows.Add(new object[] { null, "Two", "Extra 2" });
                dtMocked.Rows.Add(new object[] { null, "Three", "Extra 3" });
                dtMocked.Rows.Add(new object[] { null, "Four", "Extra 4" });
                dtMocked.Rows.Add(new object[] { null, "Five", "Extra 5" });
                CheckedListBox1.DataSource = dtMocked;
                CheckedListBox1.DisplayMember = "ItemName";
            }
    
            /// <summary>
            /// Show current checked item
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void ViewDataButton_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    if (CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
                    {
                        DataRow row = ((DataRowView)CheckedListBox1.SelectedItem).Row;
    
                        Console.WriteLine(
                            "ID: {0} field data: {1}",
                            row.Field<int>("Identifier"),
                            string.Join(",", row.ItemArray));
    
                        // since our data source is private no need to cast DataSource
                        // of the CheckedListBox
                        dtMocked.Rows.Remove(row);
    
                    }
                    else
                    {
                        Console.WriteLine($"{CheckedListBox1.Text} not checked");
                    }
                }
            }
            /// <summary>
            /// Remove current checked item
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeCurrentRowButton_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    if (CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
                    {
                        // even though we have declared our data source private thus no reason to do the casting
                        // but wanted to show how to.
                        ((DataTable)CheckedListBox1.DataSource).Rows.Remove(((DataRowView)CheckedListBox1.SelectedItem).Row);
                    }
                    else
                    {
                        Console.WriteLine($"{CheckedListBox1.Text} not checked");
                    }
                }
            }
            /// <summary>
            /// Remove/clear all rows
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeAllRows_Click(object sender, EventArgs e)
            {
                // even though we have declared our data source private thus no reason to do the casting
                // but wanted to show how to.
                ((DataTable)CheckedListBox1.DataSource).Rows.Clear();
            }
            /// <summary>
            /// Remove any checked rows
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeCheckedRows_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    // even though we have declared our data source private thus no reason to do the casting
                    // but wanted to show how to.
                    var dtData = ((DataTable)CheckedListBox1.DataSource);
                    var checkedItems = CheckedListBox1.IndexList();
                    foreach (var item in checkedItems)
                    {
                        Console.WriteLine($"Id in CheckedListBox: {item.Index} Primary key: {item.Identifier}");
                        dtData.Rows.Remove(item.Row);
                    }
                }
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, September 23, 2016 11:23 AM

All replies

  • Try removing the items from the associated data source. Give some details about the used data binding.

    Friday, September 23, 2016 5:27 AM
  • Hello,

    The following was put together from a MSDN code sample I did a while back.

    Full source for the code below is on OneDrive.

    Here a class is used to remember information about a Checked item and is used in a lambda statement in code block 2.

    public class CheckedData
    {
        /// <summary>
        /// Associated data row for the checked item
        /// </summary>
        public DataRow Row { get; set; }
        /// <summary>
        /// Item index in the CheckedListBox
        /// </summary>
        public int Index { get; set; }
        /// <summary>
        /// Primary key for Row property
        /// </summary>
        public int Identifier { get; set; }
    }

    Here is a language extension method so we keep this code out of where you would implement it e.g. in a form.

    public static List<CheckedData> IndexList(this CheckedListBox sender)
    {
        return
            (
                from item in sender.Items.Cast<DataRowView>()
                    .Select(
                    (data, index) =>
                        new CheckedData
                        {
                            Row = data.Row,
                            Index = index,
                            Identifier = data.Row.Field<int>("Identifier")
                        }
                    )
                    .Where((x) => sender.GetItemChecked(x.Index))
                select item
            ).ToList();
    }

    Simple demo where I load mocked data that would represent data returned from a database table. The mocked data is set to a CheckListBox.

    ViewDataButton: Shows currently checked items.

    removeChrrentButton: Remove current checked item.

    removeAllRows: clears all DataRow(s) from the source.

    Now what you are looking for, removed checked items and return the primary key which here is mocked but if the data came from a table in a database this provides the key to do work in the database table. 

    using System;
    using System.Data;
    using System.Windows.Forms;
    
    namespace CheckListBoxSimple_C_Sharp_1
    {
        public partial class Form1 : Form
        {
            public Form1()   { InitializeComponent(); }
    
            // Used to simulate data coming from a database table
            DataTable dtMocked = new DataTable();
    
            void Form1_Load(object sender, EventArgs e)
            {
                dtMocked.Columns.Add(new DataColumn
                {
                    ColumnName = "Identifier",
                    DataType = typeof(Int32),
                    AutoIncrement = true,
                    AutoIncrementSeed = 2,
                    AutoIncrementStep = 10
                });
    
                dtMocked.Columns.Add(new DataColumn { ColumnName = "ItemName",
                    DataType = typeof(string) });
                dtMocked.Columns.Add(new DataColumn { ColumnName = "ExtraData",
                    DataType = typeof(string) });
    
                dtMocked.Rows.Add(new object[] { null, "One", "Extra 1" });
                dtMocked.Rows.Add(new object[] { null, "Two", "Extra 2" });
                dtMocked.Rows.Add(new object[] { null, "Three", "Extra 3" });
                dtMocked.Rows.Add(new object[] { null, "Four", "Extra 4" });
                dtMocked.Rows.Add(new object[] { null, "Five", "Extra 5" });
                CheckedListBox1.DataSource = dtMocked;
                CheckedListBox1.DisplayMember = "ItemName";
            }
    
            /// <summary>
            /// Show current checked item
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void ViewDataButton_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    if (CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
                    {
                        DataRow row = ((DataRowView)CheckedListBox1.SelectedItem).Row;
    
                        Console.WriteLine(
                            "ID: {0} field data: {1}",
                            row.Field<int>("Identifier"),
                            string.Join(",", row.ItemArray));
    
                        // since our data source is private no need to cast DataSource
                        // of the CheckedListBox
                        dtMocked.Rows.Remove(row);
    
                    }
                    else
                    {
                        Console.WriteLine($"{CheckedListBox1.Text} not checked");
                    }
                }
            }
            /// <summary>
            /// Remove current checked item
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeCurrentRowButton_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    if (CheckedListBox1.GetItemChecked(CheckedListBox1.SelectedIndex))
                    {
                        // even though we have declared our data source private thus no reason to do the casting
                        // but wanted to show how to.
                        ((DataTable)CheckedListBox1.DataSource).Rows.Remove(((DataRowView)CheckedListBox1.SelectedItem).Row);
                    }
                    else
                    {
                        Console.WriteLine($"{CheckedListBox1.Text} not checked");
                    }
                }
            }
            /// <summary>
            /// Remove/clear all rows
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeAllRows_Click(object sender, EventArgs e)
            {
                // even though we have declared our data source private thus no reason to do the casting
                // but wanted to show how to.
                ((DataTable)CheckedListBox1.DataSource).Rows.Clear();
            }
            /// <summary>
            /// Remove any checked rows
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void removeCheckedRows_Click(object sender, EventArgs e)
            {
                if (CheckedListBox1.SelectedIndex > -1)
                {
                    // even though we have declared our data source private thus no reason to do the casting
                    // but wanted to show how to.
                    var dtData = ((DataTable)CheckedListBox1.DataSource);
                    var checkedItems = CheckedListBox1.IndexList();
                    foreach (var item in checkedItems)
                    {
                        Console.WriteLine($"Id in CheckedListBox: {item.Index} Primary key: {item.Identifier}");
                        dtData.Rows.Remove(item.Row);
                    }
                }
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, September 23, 2016 11:23 AM