user1108948
user1108948

Reputation:

Add items to list from configurationfile

The current code: manually setting.

<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>

In the configuration file, if I put items in

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

Then how can I retrieve them from code?

Upvotes: 0

Views: 106

Answers (2)

Garrett Vlieger
Garrett Vlieger

Reputation: 9494

You can do something like this:

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

Upvotes: 1

alexn
alexn

Reputation: 58982

You can use the ConfigurationManager class and specifically the AppSettings property. Like this:

ConfigurationManager.AppSettings["Question1"];

Do not forget to add a reference to System.Configuration.

Upvotes: 2

Related Questions