繁体   English   中英

在C#中将工具箱控件作为参数传递给方法

[英]Passing a toolbox control to a method as parameter in c#

我试图在我的网站中开发一个动态创建的工具箱控件 ,我需要使它尽可能高效。 我有以下两个条件:

private void produceControls()
{
    if (General.survey_answer_type_id == 3)
        {
            rbtnList = new RadioButtonList();
            rbtnList.ID = "ControlID_3";
            SqlDataReader dr_answer = cmd.ExecuteReader();
            while (dr_answer.Read())
            {
                rbtnList.Items.Add(dr_answer["answer"].ToString());
            }

            PlaceHolder1.Controls.Add(rbtnList);
        }
    else if (General.survey_answer_type_id == 4)
        {
            chkBoxList = new CheckBoxList();
            chkBoxList.ID = "ControlID_4";
            SqlDataReader dr_answer = cmd.ExecuteReader();
            while (dr_answer.Read())
            {
                chkBoxList.Items.Add(dr_answer["answer"].ToString());
            }
            PlaceHolder1.Controls.Add(chkBoxList); 
        }
}

除了工具箱控件名称本身以外,这些条件都相同。 我需要有一种方法可以在声明为的适当条件下使用(这只是一个抽象):

public void foo(var toolbox_name)
{
        toolbox_name = new RadioButtonList();
        toolbox_name.ID = "ControlID_3";
        SqlDataReader dr_answer = cmd.ExecuteReader();
        while (dr_answer.Read())
        {
            toolbox_name.Items.Add(dr_answer["answer"].ToString());
        }
}

然后我想像这样使用它:

private void produceControls()
    {
        if (General.survey_answer_type_id == 3)
            {
                foo(rbtnList);
            }
        else if (General.survey_answer_type_id == 4)
            {
                foo(chkBoxList);
            }
    }

我怎样才能做到这一点? 谢谢。

我只需要知道CheckBoxlistRadioButtonList的父类是什么。 它只是ListControl

例如:

public void showListControl(ListControl lstcontrol)
{
        lstcontrol.ID = "ControlID_3";
        SqlDataReader dr_answer = cmd.ExecuteReader();
        while (dr_answer.Read())
        {
            lstcontrol.Items.Add(dr_answer["answer"].ToString());
        }
}

然后像这样使用它:

RadioButtonList rbtnList = new RadioButtonList();
showListControl(rbtnList);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM