从配置文件添加项目到列表

时间:2011-12-28 18:55:40

标签: asp.net

当前代码:手动设置。

<asp:DropDownList ID="Question" runat="server">
  <asp:ListItem>What is the city of your birth?</asp:ListItem>
  <asp:ListItem>What school did you attend for sixth grade?</asp:ListItem>
  <asp:ListItem>What is your maternal grandmother's maiden name?</asp:ListItem>
  <asp:ListItem>Where were you when you had your first kiss?</asp:ListItem>
  <asp:ListItem>Who was your childhood hero?</asp:ListItem>
</asp:DropDownList>

在配置文件中,如果我将项目放在

<appSettings>
    <add key="Question1" value="What is the city of your birth?" />

然后如何从代码中检索它们?

2 个答案:

答案 0 :(得分:2)

您可以使用ConfigurationManager类,特别是AppSettings属性。像这样:

ConfigurationManager.AppSettings["Question1"];

不要忘记添加对System.Configuration的引用。

答案 1 :(得分:1)

您可以这样做:

int i = 1;

string question = null; 

do {
   question = System.Configuration.ConfigurationManager.AppSettings["Question" + i.ToString()]; 

   if (question != null) {
     Question.Items.Add(new ListItem(question, i.ToString()));
     i++;
   }
} while (question != null);