【问题标题】:Error at define Sql Connection in winform c#在winform c#中定义Sql Connection时出错
【发布时间】:2015-10-14 10:53:18
【问题描述】:

我在我的 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>

我的 c# 代码是:

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();

        }
    }
}

但是这一行有错误:

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

然后说:

错误 1 ​​类型或命名空间名称“ConfigurationManager”不 存在于命名空间“System.Configuration”中(您是否缺少 程序集参考?) D:\visual studio 项目\项目\LocalService1\LocalService1\signup.cs 35 72 LocalService1

【问题讨论】:

标签: c# winforms connection-string sqlconnection sqlcommand


【解决方案1】:

您应该在您的项目中添加引用 System.Configuration.dll

右击项目,从Add菜单,点击Reference...,在对话框中搜索System.Configuration.dll并点击复选框勾选,然后点击确定。

  • 如果您使用的是 VS2010,则无法搜索,您应该从 .Net 选项卡中选择 dll
  • 如果您使用的是 VS2013,您可以选择 Assemblies -> Framework 节点。

【讨论】:

    【解决方案2】:
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localservice"].ToString());
    

    您在 web.config 中被赋予不同的名称,但在 C# 中,您在 ConnectionStrings["localservice"]

    中被赋予不同的名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多