c# - 解决错误 "The ConnectionString property has not been initialized."?

标签 c# asp.net

我的代码是查看gridview中的所有数据

Web.config代码是

<configuration>
  <connectionStrings>
    <add name="ConStr" connectionString="DataSource=.;Integrated Security=SSPI;Initial catalog=sshopping"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>

在外部类中编码

namespace DBAction
{
    public class ViewAction
    {
        public DataSet GetAllData()
        {
                SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
                cmd.CommandText = "Select UserName,Password,RoleName,EmailID,SecurityQuestion,SecurityAnswer,LastLogin from LoginInfo";
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();  
                da.Fill(ds);
                cmd.Dispose();
                DataConnection.CloseConnection();
                return ds;
        }
    }
}

它在 da.Fill(ds) 行给出错误 将数据源与 gridview 绑定(bind)的代码在页面加载时编码如下。

 DataSet ds = new ViewAction().GetAllData();
        gvLoginInfo.DataSource = ds;
        gvLoginInfo.DataBind();

而数据连接类中的conectionstring代码为

 public static SqlConnection GetConnection()
        {

            if (con == null)
            {
                con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
                con.Open();
            }

             return con;
        }

一一错误是

Exception Details: System.ArgumentException: Keyword not supported: 'datasource'.

Source Error:


Line 19:             {
Line 20:                 con = new SqlConnection();
Line 21:                 con.ConnectionString =ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
Line 22:                 con.Open();
Line 23:             }

最佳答案

错误仅在 Web.Config 中。请在 connectionString 中的 DataSource 之间加一个空格,如:Data Source。因此您的连接字符串将变为:

 "Data Source=.;Integrated Security=SSPI;Initial catalog=sshopping".

关于c# - 解决错误 "The ConnectionString property has not been initialized."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17509476/

相关文章:

c# - 如何进行 ASP.NET 依赖注入(inject)

c# - 不从 c# 中的字符串中修剪空格

c# - MVC 6 - 参数 URL 上的 Web API 2.0 空白

asp.net - 在 ASP.NET 中的数据转发器内部绑定(bind)数据转发器

c# - 重写 ASP.NET 代码隐藏文件中的 Page 类构造函数——何时调用?

c# - Monodevelop 中的 MySQL ASP.NET MVC

c# - .NET Core 从项目中排除一个类

c# - 通过 LINQ 检查分隔字段中的值

asp.net - WSFederation 登录 - Asp.net 4.6.1

c# - VistaFolderBrowserDialog 未从正确的文件夹开始