gpt4 book ai didi

C# SqlCommand Connection.Open() 问题

转载 作者:行者123 更新时间:2023-11-30 13:50:50 26 4
gpt4 key购买 nike

我有一个 C# ASP.NET Web 应用程序,我正在尝试使用数据库表中的列填充 ASP:DropDownList。

我的代码:

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

当我运行该页面时出现以下错误

The ConnectionString property has not been initialized.

指向 cmd.Connection.Open(); 我不明白为什么,SQL 连接存储在我的 web.config 文件中。

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的名义.

关于C# SqlCommand Connection.Open() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5460659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com