Home > OS >  How to get the tag of selected item in CheckedListBox C#
How to get the tag of selected item in CheckedListBox C#

Time:02-16

I have this code that fills the CheckedListBox with values from SQL

using( dtbname db = new dtbname())
{
string query="select id, name from table where status=1";
var rec= db.Database.SqlQuery<IdName>(query).ToList(); **//the IdName is a get set file**
foreach (var item in rec)
{
checkedListBox1.Items.Add(item.name);
checkedListBox1.Tag = item.id;
}
}

Now I see that the tag is filled with the ID values when I follow it with debug but I want to make it with a button that when I select one name, its tag is printed on MessageBox. I tried just making

MessageBox.show(checkedListBox1.Tag.ToString()); 

But just prints the last ID from the list when there are many names with id.

CodePudding user response:

you can also try to use listview and give checkbox from the properties

using( dtbname db = new dtbname())
{
string query="select id, name from table where status=1";
var rec= db.Database.SqlQuery<IdName>(query).ToList(); **//the IdName is a get set file**
foreach (var item in rec)
{
var listview = new listview(item.name){
tag = item.id;
};
listview.items.add(listview);
}

and then to get the tag of selected checkbox is

messagebox.show(listview.checkeditems[0].tag.ToString());

CodePudding user response:

Well in your loop each time you are replacing the Tag value, so its value will be the last item's id:

foreach (var item in rec)
{
    checkedListBox1.Items.Add(item.name);
    checkedListBox1.Tag = item.id;  // <= in here
}

I suggest that you make a little change to your IdName class and override its ToString() method:

public class IdName
{
     public string name { get; set;}
     public int id {get; set;}
     public override string ToString() => name;
} 

and then add the item itself instead of its name.

foreach (var item in rec)
{
    checkedListBox1.Items.Add(item);
}

now you can access any items id.

foreach(IdName item in checkedListBox1.SelectedItems)
{
    MessageBox.Show(item.id.ToString());
}
  • Related