Search code examples
c#.netwinformscheckedlistbox

How can I get the item ID in a CheckedListBox?


I have a method that pulls a url name(varchar), a urlID(int) and its Enabled status(bit) from a database and populates the results to a CheckedListBox on a foreach loop. The problem I have is the checkedboxlist only seems to take a name and its checked status. What i need to be able to do is when a user has finished with there selections on a button event it reads CheckedListBox and gets the URL ID, and enabled status so I can then write this back to the database.

This is the code I am using:

/// <summary>
/// Create url names in check box list.
/// </summary>
/// <param name="rows"></param>
private void CreateURLCheckBoxes(DataRowCollection rows)
{
    try
    {
        int i = 0;
        foreach (DataRow row in rows)
        {
            //Gets the url name and path when the status is enabled. The status of Enabled / Disabled is setup in the users option page
            string URLName = row["URLName"].ToString();
            int URLID = Convert.ToInt32(row["URLID"]);
            bool enabled = Convert.ToBoolean(row["Enabled"]);

            //Adds the returned to rows to the check box list
            CBLUrls.Items.Add(URLName, enabled);

        }
        i++;
    }

    catch (Exception ex)
    {
        //Log error
        Functionality func = new Functionality();
        func.LogError(ex);

        //Error message the user will see
        string FriendlyError = "There has been populating checkboxes with the urls ";
        Classes.ShowMessageBox.MsgBox(FriendlyError, "There has been an Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Solution

  • Step 1: Create a class to hold the Name and Id with a ToString() override that returns the Name

    public class UrlInfo
    {
        public string Name;
        public int Id;
        public bool Enabled;
    
        public override string ToString()
        {
            return this.Name;
        }
    }
    

    Step 2: Add instances of this class to your CheckedListBox

     UrlInfo u1 = new UrlInfo { Name = "test 1", Id = 1, Enabled = false };
     UrlInfo u2 = new UrlInfo { Name = "test 2", Id = 2, Enabled = true };
     UrlInfo u3 = new UrlInfo { Name = "test 3", Id = 3, Enabled = false };
    
     checkedListBox1.Items.Add(u1, u1.Enabled);
     checkedListBox1.Items.Add(u2, u2.Enabled);
     checkedListBox1.Items.Add(u3, u3.Enabled);
    

    Step 3: Cast SelectedItem to UrlInfo and retrieve the .Id

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        UrlInfo urlInfo = checkedListBox1.Items[e.Index] as UrlInfo;
        if (null != urlInfo)
        {
            urlInfo.Enabled = e.NewValue == CheckState.Checked;
            Console.WriteLine("The item's ID is " + urlInfo.Id);
        }
    }