如何为两个复选框设置不同的事件?

时间:2015-09-24 08:37:48

标签: c# visual-studio-2012

我有两部分代码:

private void Simulink_CheckedChanged_1(object sender, EventArgs e)
{
    string installerfilename = path + "installer.ini";
    string installertext = File.ReadAllText(installerfilename);
    var lin = File.ReadLines(Path.Combine(path, "installer.ini")).ToArray();

    CheckBox cb = sender as CheckBox;
    if (cb.Checked)
    {
        var product = lin.Select(line => Regex.Replace(line, "product=all", "#product=all"));
        var product_tool = product.Select(line => Regex.Replace(line, "#product=Simulink", "product=Simulink"));
        File.WriteAllLines(installerfilename, product_tool);
    }
    else if (!cb.Checked)
    {
        return;
    }
}

private void  AerospaceBlockset_CheckedChanged(object sender, EventArgs e)
{
    string installerfilename = path + "installer.ini";
    string installertext = File.ReadAllText(installerfilename);
    var lin = File.ReadLines(Path.Combine(path, "installer.ini")).ToArray();

    CheckBox cb1 = sender as CheckBox;
    if ( cb1.Checked )
    {

        var product = lin.Select(line => Regex.Replace(line, "product=all", "#product=all"));
        var product_tool = product.Select(line => Regex.Replace(line, "#product=AerospaceBlockset", "product=AerospaceBlockset"));
        File.WriteAllLines(installerfilename, product_tool);
    }

    else if (!cb1.Checked)
    {
        return;
    }
}

第二个与第一个相同,换句话说,如果我在installer.ini文件中检查Simulink checkboxAerospaceBlockset checkbox或两者都会产生同样的事情:

product=all => #product=all
#product=Simulink=> product=Simulink

要正常工作需要出现在instaler.ini文件中:

product=all => #product=all
    #product=Simulink=> product=Simulink

如果选择Simulink checkbox并且:

product=all => #product=all
    #product=AerospaceBlockset=> product=AerospaceBlockset

如果选择AerospaceBlockset checkbox

我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

您可以将两个复选框的tag属性设置为所需的字符串,然后更改行

var product_tool = product.Select(line => Regex.Replace(line, "#product=AerospaceBlockset", "product=AerospaceBlockset"));

var product_tool = product.Select(line => Regex.Replace(line, "#product=" + ((sender as CheckBox).Tag as string), "product=" + ((sender as CheckBox).Tag as string)));

最后对两个复选框使用相同的函数。

答案 1 :(得分:0)

在表单的构造函数中(假设WinForms),您可以为您的复选框连接事件,如下所示:

Simulink.CheckedChanged += Simulink_CheckedChanged_1;
AerospaceBlockset.CheckedChanged += AerospaceBlockset_CheckedChanged;

(您可能必须删除设计器中的条目,因此您不能两次调用这些方法。)

这样,复选框将执行各自的事件。由于他们的行为大多相同,你可以考虑将该逻辑提取到另一个方法中,然后用拟合参数调用它:

private void Simulink_CheckedChanged_1(object sender, EventArgs e)
{
    ProcessIniFile("Simulink");
}

ProcessIniFile中,您可以在事件方法中执行您现在正在执行的操作,但使用传入的参数替换硬编码值。