2011-12-13 51 views
1

所以我把我的代碼是這樣的:試圖解釋ASP.Net錯誤

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
    CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 
</asp:Content> 
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 

<% 
    using System.Data.SqlClient 
     public Static Main { 
connection = new SqlConnection(); 

connection.ConnectionString = "Data Source=localhost:8080;Initial Catalog=dbo.Table1;"; 
connection.Open(); 

dataadapter = new SqlDataAdapter("select * from customers", connection); 
     } 
%> 

    <h2>This is a test for a database connection</h2> <%Response.Write(dataadapter) %> 

</asp:Content> 

而且我得到了以下錯誤消息:

Source Error: 

Line 6: using System.Web.UI.WebControls; 
Line 7: 
Line 8: public partial class _Default : System.Web.UI.Page 
Line 9: { 
Line 10:  protected void Page_Load(object sender, EventArgs e) 

我能擺脫它的唯一的事情就是我可能會錯誤地輸入一些代碼?這個錯誤對我來說很不透明。

我的語法有什麼問題嗎?

+0

是否有錯誤消息?或者它真的只是說'源錯誤'? – David 2011-12-13 20:01:33

回答

1

以下行並沒有真正意義:

public Static Main 

這是一類?一個接口?

即使您將其更改爲靜態類,您也可以在不聲明它們的情況下使用變量,並嘗試在任何方法體外執行代碼。

你想要這塊代碼做什麼?

1

你去打倒你的基礎架構之前先快速瀏覽一下這篇文章:

http://www.dotnetperls.com/sqldataadapter

有一些你的實現是缺少很基本的東西。本文很好地解釋了使用SqlDataAdapter連接和查詢數據庫的要點。

1

將您的代碼從頁面中取出以測試連接並將其置於Page_Load事件中的代碼隱藏文件內。

遠離頁面中的內嵌代碼,直到您完全理解它爲止。

在你的代碼嘗試是這樣的

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
    CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 
</asp:Content> 
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 

    <asp:label id = "lblLabel" runat="server"/> 

</asp:Content> 

背後又名」 defaul.aspx.cs文件請嘗試以下

using System.Data.SqlClient; 

public partial class Default: System.Web.UI.Page 
{ 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     connection = new SqlConnection(); 

     connection.ConnectionString = "Data Source=localhost:8080;Initial Catalog=dbo.Table1;"; 
connection.Open(); 

     dataadapter = new SqlDataAdapter("select * from customers", connection); 

     lblLabel.Text = //something 

    } 
} 

Page_Load方法運行每次頁面回發時到服務器並重新加載到瀏覽器中,它的功能與Winforms或Console應用程序中的Main()方法類似,後面的代碼(.cs)通常包含大部分功能,而.aspx文件包含您的設計。可以包含邏輯,但它變成了一個全新的di當你把兩個世界混合在一起時,它就會變得不同。在熟悉混合風格之前,首先要了解基本知識。

我編碼的只是一個樣本。有關sqlDataAdapter的更深入的描述,請參閱MSDN上的這篇文章。

sqlDataAdapter Article