将工具箱控件作为参数传递给c#中的参数

时间:2014-09-22 15:57:55

标签: c# asp.net sql-server controls toolbox

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

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);
            }
    }

我怎么能实现这个目标? 谢谢。

1 个答案:

答案 0 :(得分:0)

我只需要知道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);