从字符串中获取对象的名称并以这种方式使用它

时间:2013-11-05 21:37:22

标签: c# loops checkbox checklistbox

标题可能没有我能在这里做的那么多......

假设我有5个checklistbox .. ..对于其中每个我想要一个复选框我可以点击检查/取消选中相应的检查表框中的所有元素..

我可以通过在检查/取消选中列表中所有元素的每个复选框上使用CheckedChanged来轻松完成此操作。但我想为每个列表创建一个函数..我该怎么做?我正在思考这个问题。

    private void internalModsChkAll_CheckedChanged(object sender, EventArgs e)
    {
        testfunktion("internalModsChkAll", "internalModsChkList");
    }

    private void testfunktion(string from, string to) 
    {
        if ([from].Checked == true)
        {
            for (int i = 0; i < [to].Items.Count; i++)
            {
                [to].SetItemChecked(i, true);
            }
        }
        else
        {
            for (int i = 0; i < [to].Items.Count; i++)
            {
                [to].SetItemChecked(i, false);
            }
        }
    }

我希望你能看到我在这里尝试做什么..但是上面的方法不起作用:(

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

假设WinForms,我认为你正在寻找Controls.Find()和一个演员:

    private void testfunktion(string from, string to) 
    {  
        Control[] matches = this.Controls.Find(from, true);
        if (matches.Length > 0 && matches[0] is CheckBox)
        {
            CheckBox CB = (CheckBox)matches[0];
            matches = this.Controls.Find(to, true);
            if (matches.Length > 0 && matches[0] is CheckedListBox)
            {
                CheckedListBox CLB = (CheckedListBox)matches[0];
                for (int i = 0; i < CLB.Items.Count; i++)
                {
                    CLB.SetItemChecked(i, CB.Checked);
                }    
            }
        }
    }

答案 1 :(得分:0)

正如lazyberezovsky所建议的那样,与原始帖子中的代码相同,但正在工作,其他人可以看到: - )

    private void internalModsChkAll_CheckedChanged(object sender, EventArgs e)
    {
        checkAll(internalModsChkAll, internalModsChkList);
    }

    public void checkAll(CheckBox from, CheckedListBox to) 
    {
        if (from.Checked == true)
        {
            for (int i = 0; i < to.Items.Count; i++)
            {
                to.SetItemChecked(i, true);
            }
        }
        else
        {
            for (int i = 0; i < to.Items.Count; i++)
            {
                to.SetItemChecked(i, false);
            }
        }
    }