在一个asp:占位符中随机显示多个​​用户控件

时间:2013-08-12 08:42:22

标签: c# asp.net

我有一个带有三个用户控件的webform,其中包含三个asp:占位符,其中包含需要从一组总共20个问题中随机化的问题(所以,20个用户控件):

const string randomQuestion1 = "~/Qset1";
const string randomQuestion2 = "~/Qset2";
const string randomQuestion3 = "~/Qset3";
const string randomQuestion4 = "~/Qset4";
const string randomQuestion5 = "~/Qset5";


void Page_Load(object sender, EventArgs e)
{ 
    string questionPath1 = GetRandomQuestionPath1();
    string questionPath2 = GetRandomQuestionPath2();
    string questionPath3 = GetRandomQuestionPath3();

    Control question1 = Page.LoadControl(questionPath1);
    Control question2 = Page.LoadControl(questionPath2);
    Control question3 = Page.LoadControl(questionPath3);

    PlaceHolder1.Controls.Add(question1);
    PlaceHolder2.Controls.Add(question2);
    PlaceHolder3.Controls.Add(question3);
}


protected void btnSubmit_Click(object sender, EventArgs e)
{
    // add data to database...       
}

}

private string GetRandomQuestionPath1() 
{
    Random rnd = new Random(); 
    string[] files = Directory.GetFiles(MapPath(randomQuestion1), "*.ascx");
    string questionPath = Path.GetFileName(files[rnd.Next(files.Length)]); 

    return Path.Combine(randomQuestion1, questionPath);
} 

private string GetRandomQuestionPath2() 
{
    Random rnd = new Random(); 
    string[] files = Directory.GetFiles(MapPath(randomQuestion2), "*.ascx");
    string questionPath = Path.GetFileName(files[rnd.Next(files.Length)]); 

    return Path.Combine(randomQuestion2, questionPath);
}

private string GetRandomQuestionPath3() 
{
    Random rnd = new Random(); 
    string[] files = Directory.GetFiles(MapPath(randomQuestion3), "*.ascx");
    string questionPath = Path.GetFileName(files[rnd.Next(files.Length)]); 

    return Path.Combine(randomQuestion3, questionPath);
}

如何在一个asp:placeholder中放置三个用户控件,并从一个目录而不是几个目录中随机化这些用户控件?

谢谢:)

编辑:

另外,我想获得三个随机用户控件的属性。这些用户控件只包含一个文本框。 如果静态添加usercontrol,我可以获取属性。动态添加时会很脆弱。使用<%@ Reference Control =“〜/ Qset1 / qOne.ascx”%>在aspx文件中。

0 个答案:

没有答案