请问,ListBox如何Contains
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.DisplayMember = "UserID";
listBox1.ValueMember = "Name";
}
private void button1_Click(object sender, EventArgs e)
{
List<Class1> list = new List<Class1>();
list.Add(new Class1() { UserID = 1, Name = "A" });
list.Add(new Class1() { UserID = 2, Name = "B" });
list.Add(new Class1() { UserID = 3, Name = "C" });
listBox1.DataSource = list;
}
}
class Class1
{
public int UserID { get; set; }
public string Name { get; set; }
}
listBox1的项是Class1对象,如果要判断是否Contains,怎么判断?比如我要判断listBox1是否包含1那一项,难道是
if(listBox1.Items.Contains(1)),这样写正确吗?
------解决方案--------------------
设置了 DataSource ,Items 里就是空的,不能通过 Items.Contains 了,
如果要判断,可以这样
C# code
if (((List<Class1>)listBox1.DataSource).Exists(v1 => v1.UserID == 1))
{
// ......
}
------解决方案--------------------
可以这样写,不过没楼上简单
C# code
private bool IsContains()
{
bool flag = false;
foreach (var item in listBox1.Items)
{
Class1 cl = item as Class1;
if (cl.UserID == 1 || cl.Name == "A") ;
return true;
}
return flag;
}
------解决方案--------------------
if(listBox1.Items.Contains(new Class1() { UserID = 1, Name = "A" }))
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
C# code
List<Class1> list = new List<Class1>();//放在外面,,判断list是否包含就可以了
private void button1_Click(object sender, EventArgs e)
{
list.Add(new Class1() { UserID = 1, Name = "A" });
list.Add(new Class1() { UserID = 2, Name = "B" });
list.Add(new Class1() { UserID = 3, Name = "C" });
listBox1.DataSource = list;
}
if(list.Contains(new Class1() { UserID = 1, Name = "A" }))
{
}