我是Visual Studio的新手,正在尝试通过一些ASP.NET/C# Web表单教程。在我的代码中,我试图与我们的公司SQL Server建立数据库连接。
Visual Studio 2013SQL Server 2012
我正在学习的教程建议在Web.config中配置数据库连接字符串:
<!-- Johns Connection String to the DB -->
<connectionStrings>
<add name="DBconnection" providerName="System.Data.SqlClient" connectionString="data source=TheServerName;initial catalog=TheDatabaseName;user id=TheUserName;password=ThePassword;" />
</connectionStrings>
</configuration>
面向Web的页面是基本页面。我只想说是否建立连接。这是背后的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace CPITraining
{
public partial class TestForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var connectionFromConfiguration = WebConfigurationManager.ConnectionStrings["DBConnection"];
using (SqlConnection dbConnection = new SqlConnection(connectionFromConfiguration.ConnectionString))
{
try
{
dbConnection.Open();
ltConnectionMessage.Text = "Connection Successful.";
}
catch (SqlException ex)
{
ltConnectionMessage.Text = "Connection failed: " + ex.Message;
}
finally
{
dbConnection.Close();
dbConnection.Dispose();
}
}
}
}
}
最后,这是网页:
<%@ Page Title="Colors Example" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TestForm.aspx.cs" Inherits="CPITraining.TestForm" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<h3>Your application description page.</h3>
<p>Use this area to provide additional information.</p>
<p> </p>
<p> </p>
<asp:Literal ID="ltConnectionMessage" runat="server" />
<div>
<asp:Literal ID="ltOutput" runat="server" />
</div>
</asp:Content>
我一直在获取名称'ltConnectionMessage'在当前上下文中不存在'。
不确定如何解决此错误。谢谢你的帮助。约翰
[我发现了三个更好的教程,它们在一起提供了一种使用C#在ASP.NET中站立网格视图的合理构造方法。我不确定在此处发布教程是否合适。我不希望我隐瞒信息,但是我也不想看起来像我在为教程做广告。教程重点也与该主题无关。