I am working on a class assignment and I'm stuck. I would like to copy listBox2(from Form1) to listBox3(from Form2). The code I have now compiles, but it does not copy the listBox2 to listBox3. Also, when I click btnAdd in Form2 is adds txtnewcourse.txt(from Form2) to listBox2(from Form1) not listBox3(from Form2) like it should. Here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
foreach (object x in listBox1.SelectedItems)
listBox2.Items.Add(x);
}
private void btnClearSelection_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
}
private void btnDeleteSelected_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
//The following foreach causes an error because every x depends on the SelectedItems, but, it is changing.
//foreach (object x in listBox1.SelectedItems)
// listBox1.Items.Remove(x);
{
int thisMany = listBox1.SelectedItems.Count;
object[] mySelection = new object[thisMany];
listBox1.SelectedItems.CopyTo(mySelection, 0); //'0' means copy from the first selected item
foreach (object x in mySelection)
listBox1.Items.Remove(x);
}
}
private void btnempty_Click(object sender, EventArgs e)
{
DialogResult choice;
choice = MessageBox.Show("Are you sure to clear the selected choices?", "Clear Selected Choices", MessageBoxButtons.YesNo);
if (choice == DialogResult.Yes)
{
listBox2.Items.Clear();
}
}
private void btnGoForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Lbox = listBox2;
form2.ShowDialog();
}
}
public partial class Form2 : Form
{
private ListBox listbox;
public ListBox Lbox
{
set
{
this.listbox = value;
}
get
{
return this.listbox;
}
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
txtNewCourse.Focus();
listBox3= this.listbox;
}
private void btnAdd_Click(object sender, EventArgs e)
{
string value = txtNewCourse.Text.ToString();
if (listBox3.Items.Contains(value))
MessageBox.Show(txtNewCourse.Text + " already exists in the list.", "Duplicate entry", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if(txtNewCourse.Text == "")
MessageBox.Show("Please enter a course.", "Empty textbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
listBox3.Items.Add(txtNewCourse.Text);
txtNewCourse.Focus();
}
}
}
}