日期:2014-05-17  浏览次数:20740 次

初学.NET为何代码写在<script>之间就行,写在后台cs文件就报错了呢
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication2.test"%> 
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<script runat="server">
    void Page_Load(Object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=(local);Initial Catalog=yaofang;User ID=sa;Password=123";
            SqlDataAdapter da = new SqlDataAdapter("select * from Table1", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataList1.DataSource = ds;
            DataList1.DataBind();
        }

    }
    void DataList1_ItemCommand(object s, DataListCommandEventArgs e)
    {
        lblMessage.Text = "触发ItemCommand";
    }

    void DataList1_EditCommand(object s, DataListCommandEventArgs e)
    {
        lblMessage.Text = "触发EditCommand";
    }

    void DataList1_DeleteCommand(object s, DataListCommandEventArgs e)
    {
        lblMessage.Text = "触发DeleteCommand";
    }
    void DataList1_UpdateCommand(object s, DataListCommandEventArgs e)
    {
        lblMessage.Text = "触发UpdateCommand";
    } 
</script>
<html> 
<head><title></title></head> 
<body> 
<form id="Form1" Runat="server"> 
<asp:Label ID="lblMessage" BackColor="yellow" Runat="Server" /> 

<asp:DataList ID="DataList1" OnItemCommand="DataList1_ItemCommand" OnEditCommand="DataList1_EditCommand" OnDeleteCommand="DataList1_DeleteCommand" OnUpdateCommand="DataList1_UpdateCommand" 
GridLines="Both" CellPadding="4" Runat="Server"> 
<ItemTemplate><%#Eval("bookname")%> 
<asp:LinkButton ID="LinkButton1" Text="编辑" CommandName="edit" Runat="Server"/> 
<asp:LinkButton ID="LinkButton2" Text="删除" CommandName="delete" Runat="Server"/> 
<asp:LinkButton ID="LinkButton3" Text="更改" CommandName="update" Runat="Server"/> 
</ItemTemplate> 

</asp:DataList> 
</form> 
</body>