C# 从按钮单击方法调用私有void函数
我试图从按钮单击方法调用私有void函数。selectedChoice的值从组合框中获取。我调试并发现selectedChoice的值被正确地提取,甚至在button click方法中的If条件中。只是函数没有被调用 每个方法都在类Form1中C# 从按钮单击方法调用私有void函数,c#,function,class,buttonclick,C#,Function,Class,Buttonclick,我试图从按钮单击方法调用私有void函数。selectedChoice的值从组合框中获取。我调试并发现selectedChoice的值被正确地提取,甚至在button click方法中的If条件中。只是函数没有被调用 每个方法都在类Form1中 namespace Test { public partial class Form1 : Form { private void button1_Click(object sender, EventArgs e)
namespace Test
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
if(selectedChoice == "ABC")
{
Function1();
Function2();
}
组合框代码-
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex!=0)
{
selectedChoice = comboBox1.SelectedItem.ToString();
}
}
我试图调用的函数被简单地定义为
private void Function1()
{
//do something
}
您正在尝试执行比较操作
selectedChoice == "ABC"
操作器不得用于管柱。此运算符将检查元素和比较器的id是否相等。请使用
selectedChoice.Equals("ABC")
相反
但是,使用以下代码调用这些方法:
private string selectedChoice = "ABC";
private void button1_Click(object sender, EventArgs e)
{
if(selectedChoice.Equals("ABC"))
{
Function1();
Function2();
}
}
private void Function2()
{
}
private void Function1()
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex!=0)
{
selectedChoice = comboBox1.SelectedItem.ToString();
}
}
如果调试显示它到达If块,那么继续进入它,使用。然后,您将发现问题是否确实在Function1或其他地方。请确保selectedItem with ABC不是ComboBox中的第一个。上面的代码在我的环境中工作。您是否有任何可能导致您描述的行为的优化、属性配置?
private string selectedChoice = "ABC";
private void button1_Click(object sender, EventArgs e)
{
if(selectedChoice.Equals("ABC"))
{
Function1();
Function2();
}
}
private void Function2()
{
}
private void Function1()
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex!=0)
{
selectedChoice = comboBox1.SelectedItem.ToString();
}
}