Can we declare variables in app.config file

I have a form that should be connected to SQL Server, and I have a drop-down list to select a list of databases and perform operations such as checking the primary key, etc. But now my connection string looks like this:

SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"); 

But besides this database, I need to accept its variable so that I can connect it to the database that I select from the drop-down list.

Can you guys help me!

+8
c # sql-server visual-studio
Nov 23 '10 at 14:09
source share
4 answers

Hmm, you can declare your variables as follows

 <appSettings> <add key="SmtpServerHost" value="********" /> <add key="SmtpServerPort" value="25" /> <add key="SmtpServerUserName" value="******" /> <add key="SmtpServerPassword" value="*****" /> </appSettings> 

and read how

 string smtpHost = ConfigurationManager.AppSettings["SmtpServerHost"]; int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpServerHost"]); 
+22
Nov 23 '10 at 14:16
source share

I think he wants a "semi-constant":

Web.config

 <?xml version='1.0' encoding='utf-8'?> <configuration> <connectionStrings> <add name="YourName" providerName="System.Data.ProviderName" connectionString="Data Source={0}; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword;" /> </connectionStrings> </configuration> 

CS file

 String Servername = "Test"; String ConnectionString = String.Format(ConfigurationManager.ConnectionStrings["YourName"].ConnectionString, ServerName); 
+2
Nov 23 2018-10-23
source share

you can use the connectionStrings tag in the app.config configuration. You can add as many as you want (giving them each separate key) and then extract them

example app.config xml (set the provider name to a valid provider, for example System.Data.SqlClient, and the corresponding connection string):

 <?xml version='1.0' encoding='utf-8'?> <configuration> <connectionStrings> <clear /> <add name="firstDb" providerName="System.Data.ProviderName" connectionString="Valid Connection String;" /> <add name="secondDb" providerName="System.Data.ProviderName" connectionString="Valid Connection String;" /> </connectionStrings> </configuration> 

an example of obtaining and listing them (in your case, you must create the corresponding elements in the drop-down list and set the values):

 ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; if (settings != null) { foreach(ConnectionStringSettings cs in settings) { Console.WriteLine(cs.Name); Console.WriteLine(cs.ProviderName); Console.WriteLine(cs.ConnectionString); } } 
+1
Nov 23 '10 at 14:16
source share

You can use the AppSettings section. Here over here .

0
Nov 23 '10 at 14:17
source share



All Articles