Accessing database connection string using app.config in C# winform

前端 未结 10 1133
遇见更好的自我
遇见更好的自我 2020-12-06 00:27

I can\'t seem to be able to access the app.config database connection string in my c# winforms app.

app.config code

   
           


        
相关标签:
10条回答
  • 2020-12-06 00:32

    This is all you need:

    System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
    
    0 讨论(0)
  • 2020-12-06 00:35
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
    <appSettings>
    
    <add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DB2013;User ID=sa;Password=MYSQL123" />
    
    </appSettings>
    
    </configuration>
    using System.Configuration;
    using System.Data.SqlClient;
    
    namespace OnlineDelete_W2013
    {
    public partial class CommodityEdit : Form
    {
       SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
    
        public CommodityEdit()
        {
            InitializeComponent();
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
               MyConnection.Open();
            }
            catch (Exception)
            {
    
                throw;
            }
    
    0 讨论(0)
  • 2020-12-06 00:37

    You are using the ConnectionStrings collection, not the AppSettings.

    ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
    
    0 讨论(0)
  • 2020-12-06 00:37

    try this

     ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString; 
    
    0 讨论(0)
  • 2020-12-06 00:39

    About this:

    I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

    I just declared a var like this and solved the problem:

    var strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
    
    0 讨论(0)
  • 2020-12-06 00:40
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = ConfigurationManager
        .ConnectionStrings["MyDBConnectionString"].ConnectionString;
    try
    {
        conn.Open();                
    }
    catch (Exception)
    {
        throw;                    
    }
    
    0 讨论(0)
提交回复
热议问题