0

I need to connect C# with SQL Server database using. My Computer Name is "LKW15480", using "SQL Server" is "LKW15480\SQLEXPRESS", DB Name is "DB1". Computer Login "Administrator" Error is "The 'configuration' element is not declared". Please Can you help me?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>`
    </startup>

<connectionString>
  
  <add name="cn" 
       
        connectionString="DataSource=LKW15480\SQLExpress;
        Initial Catalog=DB1;
        User ID=Administrator;"
        ProvideName="System.Data.sqlClient"/> 
</connectionString>
</configuration>

I am Learning about C# and SQL. I need Connect SQL Data Base and Filtering the data between two datetime.

3
  • 1
    The element name is "connectionStrings" (plural). Also, providing a User ID without a password will not work. Commented Jan 23, 2023 at 13:25
  • 2
    may be you need this:learn.microsoft.com/zh-cn/dotnet/api/… Commented Jan 23, 2023 at 13:25
  • It's a good idea to always validate your web.config file before asking a question. It's invalid. Try this: elmah.io/tools/config-validator Commented Jan 24, 2023 at 6:40

1 Answer 1

1

I believe you are using the connection String declared in web.config

You must use ConfigurationManager to access the connection strings declared in web.config. Please check the namespace of ConfigurationManager. If .dll isn't referenced, please download it.

Here's a code sample from Microsoft.

using System;  
using System.Configuration;  
using System.Data.SqlClient;  

namespace ConsoleApplication1  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            ReadProducts();  
        }  

        static void ReadProducts()  
        {  
            var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;  
            string queryString = "SELECT Id, ProductName FROM dbo.Products;";  
            using (var connection = new SqlConnection(connectionString))  
            {  
                var command = new SqlCommand(queryString, connection);  
                connection.Open();  
                using (var reader = command.ExecuteReader())  
                {  
                    while (reader.Read())  
                    {  
                        Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));  
                    }  
                }  
            }  
        }  
    }  
}
Sign up to request clarification or add additional context in comments.

1 Comment

OP would not get the reported error message if ConfigurationManager was not referenced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.