嘿伙计们所以我做了一个类,所以当用户从列表框中选择项目时,它会卸载该项目,除了问题是我无法访问列表框。我试过公开,但在form1.cs的代码中,该列表框的唯一关键是
请记住列表框的名称是ProgramslistBox 好的,我重新编辑了这篇文章;
private void button1_Click(object sender, EventArgs e)
{
if(ProgramsListbox.SelectedIndex == -1)
{
MessageBox.Show("Please select an item to uninstall!");
}
else
{
ProgramsListbox_SelectedIndexChanged("",EventArgs.Empty);
}
}
这个代码是FORM1.CS类,我有另一个名为UninstallItem.cs的类,我想要我的代码,下面是我的其他类
命名空间PC_TECH_Registery_Cleaner { class UninstallItem {
public void uninstallSelectedItem()
{
Form1 c = new Form1();
}
}
}
下面的内容仍在我的FORM1.CS课程中,我正在尝试它:
public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e)
{
//this will access the Uninstall item class so we can uninstall selected item.
UninstallItem c = new UninstallItem();
c.uninstallSelectedItem();
}
答案 0 :(得分:0)
考虑这个问题的两种简单方法是
第一个不需要重大改变
private MyClass myClass = new MyClass();
public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e)
{
myClass.DoSomething();
}
第二个要求您的类具有与当前表单中的事件处理程序的签名匹配的特定方法
public class MyClass
{
public void DoSomething(object sender, EventArgs e)
{
var listBox = (ListBox)sender;
// read selected index perhaps, or selected item maybe
}
}
然后以你的形式
private MyClass myClass = new MyClass();
protected override void OnLoad(EventArgs e)
{
this.ProgramsListBox.SelectedIndexChanged += myClass.DoSomething;
}
答案 1 :(得分:0)
在Form1.cs中创建UnIstallItem类的实例并使用它。然后按下按钮点击通话"删除选择"通过将programsListBox传递给它的UnInstaItem类的方法,它应该删除所选的项目。
public class Form1:Form
{
ListBox ProgramsListbox;
UninstallItem unistall;
public Form1(){
InitializeComponent();
uninstall = new UninstallItem();
button1.Click+= button1_Click;
}
void button1_Click(object sender, EventArgs e){
unistall.RemoveSelected(ProgramsListbox);
}
}
然后在你的外部课程中;
public class UninstallItem{
public UninstallItem{}
public void RemoveSelected(ListBox list)
{
if(list.SelectedIndex==-1)
{
MessageBox.Show("Please Select Item from List");
return;
}
list.Items.RemoveAt(list.SelectedIndex);
}
}