Search code examples
c#winformsconnection-stringsqlconnectionsqlcommand

Error at define Sql Connection in winform c#


I write this code in my app.config:

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

    </startup>
  <connectionStrings>
    <add name="localservice" providerName="System.Data.SqlClient"
          connectionString="Data Source=GROOT\SQL;Initial Catalog=localservice;Integrated Security=True" />
  </connectionStrings>

</configuration>

My c# code is :

using System;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

       private void button1_Click(object sender, EventArgs e)
        {

            int radius = 10;

            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["miztahrirtest2DB"].ToString());
            SqlCommand cmd = new SqlCommand("insert into vendor (username,password,lenght,width,radius,category) values (@username,@password,@lenght,@width,@radius,@category);SELECT SCOPE_IDENTITY()", con);
            cmd.Parameters.AddWithValue("username", textBox1.Text);
            cmd.Parameters.AddWithValue("password", textBox2.Text);
            cmd.Parameters.AddWithValue("lenght", Convert.ToInt32(textBox3.Text));
            cmd.Parameters.AddWithValue("width", Convert.ToInt32(textBox4.Text));
            cmd.Parameters.AddWithValue("radius", radius);
            cmd.Parameters.AddWithValue("category", comboBox1.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            //Int32 classid = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();

        }
    }
}

But there is an error on this line:

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["miztahrirtest2DB"].ToString());

and said :

Error 1 The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration' (are you missing an assembly reference?) D:\visual studio project\Project\LocalService1\LocalService1\signup.cs 35 72 LocalService1


Solution

  • You should add a reference System.Configuration.dll to your project.

    Right click on project, from Add menu, click Reference... and from the dialog, search for System.Configuration.dll and click the checkbox to check it, then click ok.

    • If you are using VS2010 you can't search and you should select the dll from .Net tab
    • If you are using VS2013 you can select Assemblies -> Framework node.