我正在制作一个有趣的“调查”表格,并试图通过过度复杂化过程来打破单调乏味。我有一组radiobuttonlists,我想从一串名字和一串值动态创建。这些值不是问题。它正在创造我无法弄清楚的所有放射性按钮列表。
例如,我可以继续这样做:
string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};
this.rblCSharp.Items.Clear();
for (int i = 0; i < level.GetLength(0); i++) {
this.rblCSharp.Items.Add(level[i]);
}
this.rblCSharp.RepeatDirection = RepeatDirection.Horizontal;
this.rblVbNet.Items.Clear();
for (int i = 0; i < level.GetLength(0); i++)
{
this.rblVbNet.Items.Add(level[i]);
}
this.rblVbNet.RepeatDirection = RepeatDirection.Horizontal;
......但我不想。我想做更像这样的事情:
string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};
string[] language = { "CSharp", "VbNet", "VbClassic", "Crystal", "Ssrs", "Sql2005", "UiWeb" };
for (int j = 0; j < language.GetLength(0); j++) {
this.rbl[j].Items.Clear();
for (int i = 0; i < level.GetLength(0); i++) {
this.rbl[j].Items.Add(level[i]);
}
this.rbl[j].RepeatDirection = RepeatDirection.Horizontal;
}
答案 0 :(得分:0)
您需要一种方法来引用与语言对应的RadioButtonList控件。你有一个字符串数组,所以一种方法是使用FindControl,但这不是我的偏好。
另一种方式是:
var languageControls = new List<RadioButtonList> { rblCSharp, rblVbNet, rblVbClassic, rblCrystal, rblSsrs, rblSql2005, rblUiWeb };
foreach(var rbl in languageControls)
{
rbl.Items.Clear();
// this could be a foreach instead, but I kept your original code
for (int i = 0; i < level.GetLength(0); i++)
{
rbl.Items.Add(level[i]);
}
rbl.RepeatDirection = RepeatDirection.Horizontal;
}
FindControl方法(这只有在动态创建和添加RadioButtonList控件时才有意义,而不是在标记和IntelliSense中可用)
string[] level = {"Expert", "Proficient", "Limited Experience", "No Experience"};
string[] language = { "CSharp", "VbNet", "VbClassic", "Crystal", "Ssrs", "Sql2005", "UiWeb" };
foreach (string lang in language)
{
RadioButtonList rbl = (RadioButtonList)FindControl("rbl" + lang);
if (rbl == null)
continue; // keep going through the rest, or throw exception
rbl.Items.Clear();
// this could be a foreach instead, but I kept your original code
for (int i = 0; i < level.GetLength(0); i++)
{
rbl.Items.Add(level[i]);
}
rbl.RepeatDirection = RepeatDirection.Horizontal;
}