Click here to Skip to main content
16,012,316 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i want to change my connection string after drop down list change.

What I have tried:

i have no any idea.Please help me
Posted
Updated 8-Jul-16 1:01am
Comments
Suvendu Shekhar Giri 8-Jul-16 5:47am    
Where have you kept the connection string ?
in the web.config?
manishbg 8-Jul-16 5:51am    
yes , but change through c#
Member 14070320 12-Feb-19 6:44am    
please answer her question!!!!

If you want to change the connection string dynamically then web.config is not probably the right place to keep the value. That's because, these are readonly peoperties.

1. If you the list in the dropdown is fixed then you can keep multiple connection strings in the same web.config file with dfferent name/key and accordingly you can switch among them.
2. If you want to modify connection string then Settings will suit more.
For detailed help on Settings check following MSDN link
Using Settings in C#[^]

Try these approaches and in case you face any issue, please let me know.

Hope, it helps :)
 
Share this answer
 
Comments
Animesh Datta 8-Jul-16 6:40am    
My 5!
Suvendu Shekhar Giri 8-Jul-16 8:40am    
Thanks :)
You can't change the connection string in the config, you either have to have all possible connections in the config and choose which one to use in your code, or create the connection dynamically

XML
<connectionStrings>
  <add name="MyCon1" connectionString="server=.\SQL2008; database=DB1; Trusted_Connection=true;"/>
  <add name="MyCon2" connectionString="server=.\SQL2008; database=DB2; Trusted_Connection=true;"/>
  <add name="MyCon3" connectionString="server=.\SQL2008; database={0}; uid={1}; pwd={2};"/>
</connectionStrings>


C#
SqlConnection con = null;

if (someCondition)
{
    // use MyCon1
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon1"].ConnectionString);
}
else
{
    // use MyCon2
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon2"].ConnectionString);
}
            
// or you can construct the string manually.  I'm going to assume you want to use
// data from your controls in the string, so if you have a variable for the database
string dbToUse = "mydb";
con = new SqlConnection(string.Format("server=.;database={0};", dbToUse));

// or you could put the tokens in the connection string itself and keep it in the web config
string username = "me";
string password = "mypassword";
            
con = new SqlConnection(string.Format(ConfigurationManager.ConnectionStrings["MyCon3"].ConnectionString, dbToUse, username, password));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900