Hi,Mick
No, it's not abug with theListBox.Items.Contains() method, it's because the items of the two ListBoxes are not the same, what you see is the text of the two items are the same, but they're belong to two different objects indeed.
For example, if the items are added by Items.Add() method, then the items in both ListBoxes are of string objects, the Contains() method works just fine in this scenario, as
Code Snippet
void Form7_Load(object sender, EventArgs e)
{
listBox1.Items.Add("aaa");
listBox1.Items.Add("bbb");
listBox1.Items.Add("ccc");
}
private void button1_Click(object sender, EventArgs e)
{
if (!this.listBox2.Items.Contains(this.listBox1.SelectedItem))
{
this.listBox2.Items.Add(this.listBox1.SelectedItem);
}
}
but, if the ListBoxes are bound to different tables, the items are different between the two ListBoxes, see the sample below.
Code Snippet
void Form7_Load(object sender, EventArgs e)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("c1", typeof(int));
dt1.Columns.Add("c2");
for (int j = 0; j < 10; j++)
{
dt1.Rows.Add(j, "aaa" + j.ToString());
}
this.listBox1.DisplayMember = "c2";
this.listBox1.ValueMember = "c1";
this.listBox1.DataSource = dt1;
DataTable dt2 = new DataTable();
dt2.Columns.Add("c1", typeof(int));
dt2.Columns.Add("c2");
dt2.Rows.Add(0, "aaa" + 0.ToString());
bs.DataSource = dt2;
this.listBox2.DisplayMember = "c2";
this.listBox2.ValueMember = "c1";
this.listBox2.DataSource = bs;
}
BindingSource bs = new BindingSource();
private void button1_Click(object sender, EventArgs e)
{
if(this.listBox2.Items.Contains(this.listBox1.SelectedItem))
{ //Always FALSE. //the dataof the firstitem in the two ListBoxesyou see are seeminglythe same, //but in factthey are different objects, they're just two different DataRowView objects //with same data. //If you compare the this.ListBox1.SelectedItem.GetHashCode() //with the listBox2.Items[0].GetHashCode(), you'll find they're totally different.
}
}
Code Snippet
void Form7_Load(object sender, EventArgs e)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("c1", typeof(int));
dt1.Columns.Add("c2");
for (int j = 0; j < 10; j++)
{
dt1.Rows.Add(j, "aaa" + j.ToString());
}
this.listBox1.DisplayMember = "c2";
this.listBox1.ValueMember = "c1";
this.listBox1.DataSource = dt1;
DataTable dt2 = new DataTable();
dt2.Columns.Add("c1", typeof(int));
dt2.Columns.Add("c2");
dt2.Rows.Add(0, "aaa" + 0.ToString());
bs.DataSource = dt2;
this.listBox2.DisplayMember = "c2";
this.listBox2.ValueMember = "c1";
this.listBox2.DataSource = bs;
}
BindingSource bs = new BindingSource();
private void button1_Click(object sender, EventArgs e)
{
DataRowView drv = this.listBox1.SelectedItem as DataRowView;
if (bs.Find("c2", drv["c2"]) < 0)
{
DataTable dt = bs.DataSource as DataTable;
DataRow row = dt.NewRow();
row.ItemArray = drv.Row.ItemArray;
dt.Rows.Add(row);
}
}
Best Regards Zhi-xin Ye.
|