我需要将检查项从一个检查表添加到另一个检查表。 我不应该多次将项目添加到第二个清单框中。 该设计有两个checklistboxes和以下按钮:>,>>,<,<< 我已经尝试了下面的代码,但无法显示任何内容。请让我知道我错在哪里:
namespace TwoListBox
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public delegate void OneArrowForwardClickHandler();
public event OneArrowForwardClickHandler OneArrowForward;
private void button1_Click(object sender, EventArgs e)
{
OneArrowForward += new OneArrowForwardClickHandler(OneForward);
}
public void OneForward()
{
foreach (Object cs in checkedListBox1.CheckedItems)
{
if (!checkedListBox2.Items.Contains(cs))
checkedListBox2.Items.Add(cs.ToString());
else
{
MessageBox.Show("Item is already added");
continue;
}
}
}
public delegate void TwoArrowForwardClickHandler();
public event TwoArrowForwardClickHandler TwoArrowForward;
private void button2_Click(object sender, EventArgs e)
{
TwoArrowForward += new TwoArrowForwardClickHandler(TwoForward);
}
public void TwoForward()
{
foreach (Object cs in checkedListBox1.Items)
{
if (!checkedListBox2.Items.Contains(cs))
checkedListBox2.Items.Add(cs.ToString());
else
MessageBox.Show("Items were already added");
}
}
public delegate void OneArrowBackwardClickHandler();
public event OneArrowBackwardClickHandler OneArrowBackward;
private void button3_Click(object sender, EventArgs e)
{
OneArrowBackward += new OneArrowBackwardClickHandler(OneBackward);
}
public void OneBackward()
{
foreach (Object cs in checkedListBox1.CheckedItems)
{
checkedListBox2.Items.Remove(cs);
}
}
public delegate void TwoArrowBackwardClickHandler();
public event TwoArrowBackwardClickHandler TwoArrowBackward;
private void button4_Click(object sender, EventArgs e)
{
TwoArrowBackward +=new TwoArrowBackwardClickHandler(TwoBackward);
}
public void TwoBackward()
{
foreach (Object cs in checkedListBox1.Items)
{
checkedListBox2.Items.Remove(cs);
}
}
private void button5_Click(object sender, EventArgs e)
{
string s = "The selected items are:";
for (int i = 0; i < checkedListBox2.Items.Count - 1; i++)
{
s += checkedListBox2.CheckedItems[i].ToString() + "\n";
}
MessageBox.Show(s);
}
}
}
注意:&gt;表示添加选中的项目,&gt;&gt;意味着添加所有项目,&lt;表示删除所选项目&lt;&lt;意味着删除所有项目
答案 0 :(得分:2)
在按钮单击事件中,您只需向事件添加事件处理程序。你试过直接调用这个函数吗?
不是创建事件处理程序,而是调用每个函数,类似于在button1的click事件中调用OneForward()
的方法:
private void button1_Click(object sender, EventArgs e)
{
OneForward();
}
对评论的回应
如果您的意思是要通知家长您的按钮被点击并且OneForward已经完成,您可以在OneForward功能结束时使用以下行:
OneArrowForward(this, new EventArgs());
但是如果你想从父母那里调用OneForward,那么你必须将其公开,然后从你简单地打电话给父母:
myUserControlInstance.OneForward();