C#SqlCommand Connection.Open()问题 [英] C# SqlCommand Connection.Open() issue
问题描述
我有一个C#ASP.NET Web应用程序,我试图用数据库表中的列填充ASP:DropDownList。
I have a C# ASP.NET web application an I am trying to populate an ASP:DropDownList with a column in a database table.
我的代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;
namespace CRM2Sage
{
public partial class SOPOrderEntry : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Fill1();
}
public void Fill1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Products", new SqlConnection(WebConfigurationManager.AppSettings["CRM2Sage"]));
//cmd.Connection.Open();
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
vproduct.DataSource = ddlValues;
vproduct.DataValueField = "theName";
vproduct.DataTextField = "theName";
vproduct.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}
}
我在运行页面时我收到以下错误消息
An when I run the page I get the following error
ConnectionString属性的
尚未初始化。
The ConnectionString property has not been initialized.
指向 cmd.Connection.Open();
我不明白为什么,SQL连接存储在我的Web中。配置文件。
pointing to cmd.Connection.Open();
I can not understand why, the SQL connection is stored in my web.config file.
web.config
<?xml version="1.0"?>
<configuration>
<appSettings />
<connectionStrings>
<add name="CRM2Sage" connectionString="Data Source=W2003CRMDEMO; Initial Catalog=CRM2Sage; User ID=newSA; Password=password;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true">
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
有人可以帮忙吗?
欢呼
贾斯汀
推荐答案
您需要检索 .ConnectionString
属性:
string connectionString = WebConfigurationManager.ConnectionStrings["CRM2Sage"].ConnectionString;
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand("SELECT * FROM Products", _con))
{
// do your stuff here
}
您现在正在做的只是在找东西< connectionStrings>
下的整个条目,名称为 CRM2Sage
。
What you're doing right now is just retrieving the whole entry under <connectionStrings>
by the name of CRM2Sage
.
这篇关于C#SqlCommand Connection.Open()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!