Trouble when i am moving the list box items from listbox1 to listbox 2 in WPF?
I am trying to achieve some thing one these lines ,I have two listboxes listbox1 and listbox2 ,i have the add and delete button respectively to move the items from one listbox to another.For some reason i am unable to select the item from the list box after couple of moves .
I am using the following code
logic for Add button
ArrayList listitems1 = new ArrayList();
ArrayList listitems2 = new ArrayList();
if (listBox2.SelectedItem == null)
{
System.Windows.MessageBox.Show("*Please Select unassigned Wks ");
return;
}
else
{
try
{
foreach (string st in listBox2.Items)
{
listitems1.Add(st);
}
foreach (string st1 in listBox1.Items)
{
listitems2.Add(st1);
}
if (listBox2.SelectedIndex > -1)
{
string value = listBox2.SelectedItem.ToString();
string text = listBox2.SelectedItem.ToString();
listitems2.Add(value);
listBox1.ItemsSource = listitems2;
listitems1.Remove(value);
listBox2.ItemsSource = listitems1;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
**logic for delete button:**
ArrayList listitems1 = new ArrayList();
ArrayList listitems2 = new ArrayList();
if (listBox2.SelectedItem == null)
{
System.Windows.MessageBox.Show("*Please Select unassigned Wks ");
return;
}
else
{
try
{
foreach (string st in listBox2.Items)
{
listitems1.Add(st);
}
foreach (string st1 in listBox1.Items)
{
listitems2.Add(st1);
}
if (listBox2.SelectedIndex > -1)
{
string value = listBox2.SelectedItem.ToString();
string text = listBox2.SelectedItem.ToString();
listitems2.Add(value);
listBox1.ItemsSource = listitems2;
listitems1.Remove(value);
listBox2.ItemsSource = listitems1;
}
}
开发者_运维知识库 catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
ArrayList listitems1 = new ArrayList();
ArrayList listitems2 = new ArrayList();
try
{
foreach (string st in listBox2.Items)
{
listitems1.Add(st);
}
foreach (string st1 in listBox1.Items)
{
listitems2.Add(st1);
}
if (listBox1.SelectedIndex > -1)
{
string value = listBox1.SelectedItem.ToString();
string text = listBox1.SelectedItem.ToString();
listitems1.Add(value);
listBox2.ItemsSource = listitems1;
listitems2.Remove(value);
listBox1.ItemsSource = listitems2;
}
}
Try this. For your add method:
if (listBox2.SelectedItem == null)
{
System.Windows.MessageBox.Show("*Please Select unassigned Wks ");
return;
}
else
{
if (listBox2.SelectedIndex > -1)
{
Object obj = listBox2.SelectedItem;
listBox1.Items.Add(obj);
listBox2.Items.Remove(obj);
}
}
Do something similar for the delete method. I think the problem might be that you are using ArrayLists as the source for the ListBox items, and the ArrayLists go out of scope.
精彩评论