HTML控件... 3

HTML控件常用屬性... 3

HtmlInput控件... 4

HtmlSelect控件... 6

HtmlImage控件... 6

HtmlTable. 7

HtmlDiv控件... 8

Web控件... 8

AdRotator控件... 8

Calendar控件... 9

Substitution控件... 9

Wizard控件... 10

服務器端驗證控件... 11

ASP.NET內置對象... 19

Response對象... 19

使用Response對象... 20

使用Request對象... 21

Server對象... 23

使用Server對象... 25

Session對象... 26

使用Session對象... 26

導航控件... 28

TreeView控件... 28

SiteMapPath控件... 29

Menu控件... 30

常用功能... 31

字符串的處理... 31

DataGrid使用... 33

Panel橫向滾動,縱向自動擴展... 37

格式化... 37

頁面間的操作... 43

其他功能... 46

GridView的分頁和排序... 46

GridView的常用功能... 46

使用嵌套的Repeater控件显示分级数据... 59

文件上傳與下載功能... 65

SqlDataReadDataset的选择... 68

ExecuteNonQueryExecuteScalar 68

Session["变量"]; 68

QueryString. 69

char.IsWhiteSpce(字串變數,位元數)--邏輯型... 69

char.IsPunctuation('字元') --邏輯型... 69

Math.Max(i,j) 69

FindControl(string id) 70

CSS層疊樣式表... 70

數據庫操作... 73

显示图片... 77

创建SQL数据表语句... 79

HTML控件

HTML控件常用屬性

1 ID屬性

獲取或設置該控件的名稱。

2 Visible屬性

使用于文字、按鈕或文本框等的HTML控件。若此屬性被設為false,則該HTML標記將顯示成灰色;若該HTML控件為按鈕,則該按鈕不可操作;若該HTML控件為文本框,則該文本框中內容不可更改。

3 Style屬性

獲取或設置該控件的外觀效果,包括背景顏色、邊框顏色或空間中字符顯示格式等多種效果。

4 InnerHtml

該屬性用于設定標記對之間的HTML文件,如果InnerHtml屬性中包含有HTML標記,那么其中的HTMl標記會被瀏覽器是為HTML標記并加以翻譯。

5 InnerText

該屬性用于設定標記對之間的HTMl文字,如果InnerText屬性中包含有HTMl標記,那么其中的HTML標記會被瀏覽器視為文字,而不翻譯直接在瀏覽器中顯示。

HtmlInput控件

Input控件又稱為用戶輸入控件,與之對應的HTML標記是用戶輸入類型<input type= />。該控件類型多樣,包括ButtonResetSubmitTextRadio等。

1 Button

適用于IE4.0NetScape6.0及以上版本的瀏覽器,使用該控件時需要將其放置在<form runat=”server”></ form>標記對之間。將其作為服務器控件運行時,可以在后臺編寫OnServerClick事件。該事件發生時,執行事件下編寫的代碼。

如果該控件不是服務器控件,即沒有設置runat=”server”,雙擊該控件后進入前臺代碼編輯區編寫HTM代碼;如果該控件為服務器控件,雙擊該控件進入代碼編輯區。

<input  id=”myButton”  onclick=””  type=”button”  value=”單擊此處

Onserverclick=”myButton_ServerClick”  runat=”server”  />

2 Submit

如果Input的屬性type值為submitButton按鈕就變成Submit類型按鈕。它用于在網頁上創建一個提交窗體的按鈕控件。

<input  id=”myButton”  type=”submit”  value=”提交  runat=”server”  />

3 Reset

如果Input的屬性type值為resetButton按鈕就變成Reset類型按鈕。它將窗體控件重置為其初始值。

<input  id=”myButton”  type=”reset”  value=”重置  runat=”server”  />

4 CheckBox

Input屬性typeCheckBox時,可以組成多選框。新增Checked作為判斷條件,當Checkedtrue時表示選擇了該項,否則表示沒有被選中。該控件的Checked屬性用于判斷控件是否被選中。

<input  id=”myCheckOne”  type=”checkbox”  runat=”server”  />計算機

5 InputRadio

Input屬性typeradio時,即稱為一組單選框。通過將name屬性設置為組內所有<input type=radio>元素所共有的值,可以將多個HtmlInputRadio控件組成一組。同組中的單選按鈕互相排斥,一次只能選擇改組中的一個單選按鈕。InputRadio控件具有onserverchange事件,用于編寫處理程序來對該控件進行編程。控件不會自動向服務器發送信息,必須依賴于使用某個按鈕控件的事件,如InputSubmit來發送到服務器。

<input  type=”radio”  id=”MyRadioOne”  name=”Mode” 

runat=”server”  />選項1

<input  type=”radio”  id=”MyRadioTwo”  name=”Mode” 

runat=”server”  />選項2

<input  type=”radio”  id=”MyRadioThree”  name=”Mode” 

runat=”server”  />選項3

6 InputTextInputPassword

Input控件type屬性為textpassword時,稱為文本框控件。此時type屬性為text時成為文本輸入框,用于輸入用戶數據;當type屬性為password時,即為一個密碼輸入框,當用戶輸入信息時顯示為實心黑點,隱藏輸入的真實內容。該控件通常用于服務器端驗證是否為合法用戶。

type屬性不同的兩種控件具有相同的常用屬性。例如:value用于存儲輸入框中信息;size用于設置輸入框的大小;maxlength用于設置輸入文本字符串的最大限制。

<input  type=”text”  id=”MyID”  runat=”server”  size=”20” />

<input  type=”password”  id=”MyPwd”  runat=”server”  size=”20”  maxlength=”10”  />

7 InputFile

Input控件type屬性為inputfile時,即為一個文件上傳控件。該控件可以從瀏覽器的客戶端向服務器的指定目錄中上傳二進制文件或文本文件。

在向指定目錄中上傳文件時首先要設置該目錄文件夾,將用戶的寫入權限設為“允許”。

<input  id=”MyFile”  type=”file”  runat=”server”>

8 InputHidden

input控件的type屬性為Hidden時,將生成一個隱藏傳輸數據的控件。該控件主要用于傳輸數據而不使用CookiesSession。盡管次控件是窗體的一部分,但它永遠不在窗體上顯示。由于在HTML中不保持狀態,所以此控件通常與InputButtonInputText控件一起用于存儲在服務器之間發送的信息。

<input  id=”HiddenValue” type=”hidden” value=”初始值” runat=”server”>

HtmlSelect控件

HtmlSelectHTML標記為<select>的控件,該控件允許用戶在列表中選擇。該控件具有兩個關鍵屬性:Value屬性代表被選取的選項;Item屬性代表所有的選項,該屬性為對象集合,可利用Add()方法添加新的列表項。

<select  id=”ColorSelect”  runat=”server”>

        <option>LightGreen</ option>

        <option>Gainsboro</ option>

        <option>SkyBlue</ option></  select>

HtmlImage控件

使用HtmlImage控件的作用是顯示圖像,相當于HTML中的<img>標記。該控件具有幾種屬性:

Src  該屬性用于獲取或設置圖像的源地址。

Width  該屬性用于獲取或設置圖像高度。

Height  該屬性用于獲取或設置圖像的高度。

Border  該屬性用于獲取或設置圖像邊框的寬度。

Alt  該屬性用于獲取或設置在圖像不可用或當前正在下載且尚未完成的情況下瀏覽器顯示的替換標題;Alt屬性是HtmlImage控件的必需屬性。

Align  該屬性獲取用于設置圖像與其他網頁元素的對齊方式。

<img  alt=”正在下載….”  id=”MyImage”  src=”images/1.gif”  runat=”server” />

HtmlTable

HtmlTable控件與HTML標記中的<table>相對應,它允許用戶創建一個表。HtmlTable控件由一些行組成,行存儲在表的Rows集合中,由HtmlTableRow對象表示,相當于HTML標記中的<tr>;每行均由存儲在行Cells集合中的單元格組成,單元格由HtmlTableCell對象表示,相當于HTML標記中的<td>

HtmlTable控件中具有多種屬性,通過設置這些屬性能夠設計出令用戶滿意的表格,關鍵屬性如下所示:

BgColor  該屬性用于獲取或設置控件的背景顏色。

Border  該屬性用于獲取或設置控件的邊框寬度。

Height  該屬性用于獲取或設置控件的高度。

Width  該屬性用于獲取或設置控件的寬度。

Cellpadding  該屬性用戶獲取或設置控件中單元格內容和單元格邊框之間的間距,以像素為單位。

CellSpadding  該屬性獲取或設置控件中相鄰單元格之間的間距,以像素為單位。

Rows  該屬性獲取包含在控件中的所有行的HtmlTableRowCollection集合。屬性中又包含了諸多方法。

若要創建表,首先應在頁上的窗體中聲明一個HtmlTable<table>控件。然后,將HtmlTableRow<tr>對象放置在HtmlTable控件的開始和結束標記之間,對于表中所需的每一行放置一個對象。每個HtmlTableRow對象的開始和結束標記之間放置HtmlTableCell<td>對象以創建該行的單元格。

HtmlDiv控件

Visual Studio.NET 2005工具箱的HTML選項卡上提供一個基于HTML<div>標記的Div控件,它允許用戶在頁面上創建一個層。在設計頁面中可以隨意拖放,控制控件的大小,并且可以在該控件上隨意創建或放置其他控件。

Web控件

Web服務器控件是設計側重點不同的另一組控件。它們不必一對一地映射到HTML服務器控件,而是定義為抽象控件。Web服務器控件包括傳統的窗體控件,例如按鈕、文本框和表等復雜控件。同時還包括提供常用窗體功能,例如在網格中顯示數據、選擇日期或顯示菜單等控件。它通常以<asp: type>開始。

AdRotator控件

AdRotator Web服務器控件可從一條多多條廣告紀錄的數據源讀取廣告信息。用戶可以將信息存儲在一個XML文件或數據庫中,然后將AdRotator控件綁定到該文件,并在頁面中顯示信息。AdRotator控件的所有屬性都是可選的,XML文件中可以出線以下屬性:

ImageUrl  要顯示圖像的URL

NavigateUrl  單擊AdRotator控件是要轉到的網頁的URL

AlternateText  圖像不可用時顯示的文本

Keyword  可用于篩選特定廣告的廣告類別

Impression  一個指定廣告的可能顯示頻率的數值,加權數值。在所有XML文件中,所有Impressions值的總和不能超過2 048 000 000-1

Height  廣告的高度,以像素為單位

Width  廣告的寬度,以像素為單位

<Ad>

        <ImageUrl>~/images/1.gif</ ImageUrl>

        <NavigateUrl>http://www.163.com</NavigateUrl>

        <AlternateText>網易廣告</ AlternateText>

        <Impressions>50</ Impressions>

</ Ad>

Calendar控件

Calendar Web服務器控件在ASP.NET網頁中顯示一個單月份日歷。用戶可以使用該日歷查看和選擇日期。使用該控件的一般語法形式如下:

<asp: Calendar  ID=”MyCalendar”  runat=”server” ></ asp: Caledar>

例子:MyCalendar.SelectedDate.ToShortDateString()函數以簡短日期字串的形式返回當前選擇的日期。

Substitution控件

緩存某個ASP.NET頁時,默認情況下會緩存該頁的全部輸出。在第一次請求時,該頁面將運行并緩存其輸出。對于后續的請求,將通過緩存來完成,該頁面上的代碼不會運行。Substitution控件能夠實現上述功能,指定輸出緩存的網頁上不進行緩存的部分,同時控件無法訪問頁上的其他控件。

Substitution控件調用的方法必須符合下面的標準:

方法被定義為靜態方法;

方法接受HttpContext類型的參數;

方法返回String類型的值。

例如:

聲明一個控件:<asp: substitution  id=”MySubstitution1” 

methodname=”GetUser” runat=”server”></asp: substitution>

在后臺代碼編輯區為GetUser方法添加代碼:

public static string GetUser (HttpContext  context)

{

                return context.User.Identity.Name;

}

此例子演示如何以聲明方式將Substitution控件添加到輸出緩存網頁。Substitution控件執行時,會調用GetUser方法,該方法返回表示當前用戶的字符串。

Wizard控件

Wizard控件為用戶提供了呈現一連串步驟的基礎架構,這樣可以訪問所有步驟中包含的數據,并方便地進行前后導航。Wizard控件的導航包括線性導航(從一步轉到下一步或上一步)和非線性導航(從一步轉到任意其他步)。

使用Wizard控件的標準語法形式如下:

<asp: Wizard  ID=”Wizard1”  runat=”server”  ActiveStepIndex=”1”>

        <WizardSteps>

        <asp: WizardStep  runat=”server”  Title=”Step 1”>

        </asp: WizardStep>

        <asp: WizardStep  runat=”server”  Title=”Step 2”>

        </asp: WizardStep>

        </WizardSteps>

</asp: Wizard>

也可以在WizardStep集合編輯器中添加所需的步驟,并指定相應的屬性。每一步驟都有一個索引值,值從0開始。ActiveStepIndex屬性用來指定控件初始化時顯示的步驟,其值為各個步驟的索引值。

服務器端驗證控件

1 RequireFieldValidator控件

RequireFieldValidator控件被稱為非空驗證控件,常用于文本輸入框的非空驗證。如果使用該控件,當用戶提交頁面到服務器時,系統自動檢查被驗證控件的輸入是否為空,如果為空則顯示錯誤信息。使用該控件的一般語法形式為:

<asp: RequiredFieldValidator  ID=”MyRFV”

Runat=”server”  ErrorMessage=”出錯信息  ControlToValidate=”需要驗證的控件

Display=”Static|Dymatic|None”>

</asp: RequiredFieldValidator >

代碼中ControlToValidate屬性值為被驗證控件的ID

2 CompareValidator控件

CompareValidator控件為比較驗證控件,主要用來比較兩個TextBox控件的內容或者某個控件與某個固定表達式值是否相等。如果比較結果不相等時,顯示出錯信息。該控件在用戶修改密碼或輸入新密碼時非常有用。該控件的主要屬性有:

ControlToCompare 獲取或設置用于比較的輸入控件的ID,默認值為空;

ControlToValidate 需要驗證控件的ID

ValueToCompare 獲取或設置要比較的值;

Operator 獲取或設置驗證中使用的比較操作,默認值為Equal

Type 獲取或設置比較的兩個值的數據類型,默認值為String類型。

使用該控件的一般語法形式為:

<asp: CompareValidator  ID=”cv”  runat=”server”  ErrorMessage=””

ControlToValidate=””  ControlToCompare=””>

</asp: CompareValidator>

3 RangeValidator控件

RangeValidator控件為范圍驗證控件,如果用戶輸入的內容不在驗證范圍內時將引發頁面錯誤。控件提供了IntegerStringDateDoubleCurrency5種驗證類型。

Integer  主要用來驗證輸入是否在指定整數范圍內;

String  主要用來驗證輸入是否在指定的字符串范圍內;

Date  主要用來驗證輸入是否在指定的日期范圍內;

Double  主要用來驗證輸入是否在指定的雙精度范圍內;

Currency  主要用來驗證輸入是否在指定的貨幣范圍內。

使用該控件的標準代碼如下:

<asp: RangeValidator  ID=”MyRV”  runat=”server”  ErrorMessage=””

ControlToValidate=”需要驗證的控件  Type=”Currency|Integer|Date|Currency|String”

MinimumValue=”最小值  MaxmumValue=”最大值”>

</ asp: RangeValidator>

4 RegularExpressionValidator控件

RegularExpressionValidator控件又稱為正則表達式控件,該控件功能非常強大,用于確定輸入控件的值是否與某個正則表達式所定義的模式匹配。控件允許檢查可預知的字符列表,如身份證號、電子郵件地址、電話號碼或郵政編碼等。使用該控件的標準代碼如下:

<asp:  RegularExpressionValidator  ID=”MyREV”  runat=”server”

ControlToValidate=”需要驗證的控件  ValidationExpression=”正則表達式  ErrorMessage=”出錯信息

Display=”Dynamic”>

</asp: RegularExpressionValidator>

可以不用手工輸入正則表達式,在屬性窗口的ValidationExpress中進行選擇。

5 ValidatorSummary控件

ASP.NET程序設計中,如果頁面比較龐大而且需要驗證的控件比較多,用戶在觀察錯誤信息是可能會出現混亂。ValidatorSummary控件解決了這一難題,該控件又稱為錯誤總結控件,與其他控件相比具有一些特殊屬性:

HeaderText  控件匯總信息;

DisplayMode  錯誤信息的顯示格式,入橫向排列、豎向排列等;

ShowMessageBox  是否以彈出對話框來顯示驗證控件的錯誤;

ShowSummary  是否使用錯誤匯總信息;

EnableClientScript  是否使用客戶端驗證,系統默認值為true

6 CustomValidator控件

CustomValidator控件又被稱為自定義驗證控件,該控件允許用戶根據程序設計需要自定義控件的驗證方法。如:

用戶輸入是否能被3整除;

用戶輸入是否是合法的信用卡號;

學生管理系統中輸入的是否是本校學生證號。

這些例子在ASP.NET系統內置控件是無能為力的,這就需要開發者使用自定義驗證控件來實現上述驗證。使用該控件的標準代碼如下:

<asp: CustomValidator  ID=”MyCv”  runat=”server ”  ErrorMessage=””

OnServerValidate=””>

</asp: CustomValidator>

OnServerValidate用于指定控件觸發的事件,它是在后臺代碼編輯區進行定義的。

7 通過身份證判斷生日和性別

<%@ Page language="c#" Codebehind="CordBirthday.aspx.cs" AutoEventWireup="false" Inherits="CodeDatum.birthday.CordBirthday" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

 <HEAD>

  <title>CordBirthday</title>

  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

  <meta name="CODE_LANGUAGE" Content="C#">

  <meta name="vs_defaultClientScript" content="JavaScript">

  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

  <script language="javascript">

  function showBirthday(val)

  {

   var birthdayValue;

   if(15==val.length)

   { //15位身份证号码

    birthdayValue = val.charAt(6)+val.charAt(7);

    if(parseInt(birthdayValue)<10)

    {

     birthdayValue = '20'+birthdayValue;

    }

    else

    {

     birthdayValue = '19'+birthdayValue;

    }

    birthdayValue=birthdayValue+'-'+val.charAt(8)+val.charAt(9)+'-'+val.charAt(10)+val.charAt(11);

    if(parseInt(val.charAt(14)/2)*2!=val.charAt(14))

     document.all.sex.value='';

    else

     document.all.sex.value='';

    document.all.birthday.value=birthdayValue;

   }

   if(18==val.length)

   { //18位身份证号码

    birthdayValue=val.charAt(6)+val.charAt(7)+val.charAt(8)+val.charAt(9)+'-'+val.charAt(10)+val.charAt(11) 

   +'-'+val.charAt(12)+val.charAt(13);

    if(parseInt(val.charAt(16)/2)*2!=val.charAt(16))

     document.all.sex.value='';

    else

     document.all.sex.value='';

    if(val.charAt(17)!=IDCard(val))

    {

     document.all.idCard.style.backgroundColor='#ffc8c8';

    }

    else

    {

     document.all.idCard.style.backgroundColor='white';

    }

    document.all.birthday.value=birthdayValue;

   }

  }

  // 18位身份证号最后一位校验

  function IDCard(Num)

  {

   if (Num.length!=18)

    return false;

   var x=0;

   var y='';

   for(i=18;i>=2;i--)

    x = x + (square(2,(i-1))%11)*parseInt(Num.charAt(19-i-1));

   x%=11;

   y=12-x;

   if (x==0)

    y='1';

   if (x==1)

    y='0';

   if (x==2)

    y='X';

   return y;

  }

  // 求得xy次方

  function square(x,y)

  {

   var i=1;

   for (j=1;j<=y;j++)

    i*=x;

   return i;

  }

  </script>

 </HEAD>

 <body MS_POSITIONING="GridLayout">

  <form id="Form1" method="post" runat="server">

   <table align="center">

    <tr>

     <td align="center">身份证:<input type="text" name="idCard" id="idCard"></td>

    </tr>

    <tr>

     <td align="center">&nbsp;&nbsp;&nbsp;&nbsp;别:<input type="text" name="sex" id="sex"></td>

    </tr>

    <tr>

     <td align="center">&nbsp;&nbsp;&nbsp;&nbsp;日:<input type="text" name="birthday" id="birthday"></td>

    </tr>

    <tr>

     <td align="center"><input type="button" onclick="showBirthday(document.all.idCard.value)" value="OK"></td>

    </tr>

   </table>

  </form>

 </body>

</HTML>

8 使驗證控件對特定控件失效

將希望不驗證的控件的Causes Validation屬性設置為False

ASP.NET內置對象

 Response對象

Response對象是HttpResponse類的一個實例,它用于控制服務器發送給瀏覽器的信息,包括直接發送信息給瀏覽器、重定向瀏覽器到另一個URL或設置cookie的值。

常用屬性和方法:

1 Expires屬性

該屬性用于指定在瀏覽器緩沖存儲的頁面距離過期的時間。假如用戶在某個頁面過期之前又回到該頁面,就會顯示緩沖區中的版本。

2 ExpiresAbsolute屬性

該屬性用于指定瀏覽器中緩存頁面的確切到期日期和時間。在頁面未到期時,如果用戶情趣該也,將會顯示緩存中的頁面。如果未指定日期,則該頁面在腳本運行當天的指定時間到期;如果未指定時間,則該頁面在當天午夜到期。

3 Write方法

使用Response對象的Write方法可以將指定的字符串或者表達式的結果寫入當前的HTTP輸出中。方法其實就是嵌入到對象定義中的代碼程序,它指定了對象應怎樣處理信息。使用嵌入的方法,對象就能夠自覺地執行任務,而無需提供額外的指令。

4 End方法、Clear方法和Flush方法

使用Response對象的End方法可以立即停止頁面的執行,并得到相應的結果。在執行該方法時無需考慮是否進行了緩存輸出。在調試程序時,使用End方法可以只輸出一部分內容,以便判斷程序在何處中止或者出錯。

在不將緩存中的內容輸出的情況下,Response對象的Clear方法可以清空當前頁的緩存,只有使用了緩存輸出,才可以使用Clear方法。

使用Response對象的Flush方法可以將緩存中的內容立即顯示出來,而且使用該方法時,也必須使用緩存輸出;但是,調用該方法后,頁面可以繼續執行。

使用Response對象

1 發送信息

向瀏覽器發送信息是Response對象最常用的功能,一般是通過其Write方法實現的。其語法形式為:

Response.Write(value);

其中value表示要發送的信息,它可以是任何類型的變量或者表達式。

2 重定向瀏覽器

這是指讓瀏覽器訪問一個新的URL。其語法格式為:

Response.Redirect(Url);

其中Url是要重定向的目標地址。如果在某個功能頁碼的開頭部分添加Response.Redirect語句,就可以確保用戶首先訪問指定的頁面。

 Request對象

Request對象是HttpRequest類的一個實例,其主要功能是從客戶端獲取數據。使用該對象可以訪問任何HTTP請求傳遞的信息,包括使用POST方法或者GET方法傳遞的參數、Cookie和用戶驗證。

常用屬性和方法:

1 Cookies

此屬性用于獲取客戶端發送的cookie集合

Cookies的清空:

Cookie.Expires=[DateTime];
Response.Cookies("UserName").Expires = 0

2 FilePath

獲取當前請求的文件路徑

3 Files

獲取客戶端上載的文件

4 Path

獲取當前請求的虛擬路徑

5 PhysicalApplicationPath

獲取當前正在執行的服務器應用程序根目錄的物理文件系統路徑

6 UserHostAddres

獲取遠程客戶端IP主機地址

7 UserHostName

獲取遠程客戶端的DNS名稱

8 QueryString方法

Request對象的QueryString方法可以用來檢索HTTP查詢字符串中變量的值,通過發送表格數據或者由用戶在其瀏覽器的地址欄中輸入查詢都可以生成HTTP查詢字符串。

使用Request對象

1 獲取URL傳遞變量

Request對象的QueryString屬性可以用來獲取URL地址中”?”后面的數據,即URL附加信息。QueryString主要用于獲取HTTP協議中GET請求發送的數據。如果某個請求事件中被請求的URL地址中出現了”?”以及其后的數據,那么該請求的方式為GET。例如:在一個頁面中有如下代碼:

<form  action=”incept.aspx”  method=”get”>

        <center>

                請輸入你的姓名<input  type=”text”  name=”name” /><p>

                <input  type=”submit”  value=”發送” />

        </ center>

</ form>

在另一個頁面中添加如下代碼:

<form  id=”form1”  runat=”server”>

        <center><h4>接受GET方法傳來的數據<br></h4></center>

        <%

String name = Request.QueryString[“name”];

Response.Write(“你的姓名為:” + name);

%>

</form>

在該程序中,GET方法將傳遞的參數和參數值添加到URL地址當中,瀏覽器的地址欄中會顯示出包含這些信息的URL地址。Request對象的QueryString接受GET方法傳送的數據。

2 獲取表單傳遞值

當需要在網頁間傳遞信息時,還可以通過表單來實現。在這種情況下,表單傳遞的信息可以由Request對象的Form屬性來獲取。例如:在一個頁面中有如下代碼:

<form  action=”chap6_2.aspx”  method=”post”>

        請輸入你的姓名:<input  type=”text”  name=”name” /><br />

        請輸入你的性別:<input  type=”text”  name=”sex” /><br />

        請輸入你的職業:<input  type=”text”  name=”occupation” /><br />

        <input  type=”submit”  value=”發送  id=”submit1”  name=”submit1” />

</ form>

在另一個頁面中添加如下代碼:

<%

String  name = Request.Form[“name”];

Response.Write(“你的姓名為:” + name + “<br>”);

String  sex = Request.Form[“sex”];

Response.Write(“你的性別為:” + sex + “<br>”);

String  cooupation = Request.Form[“cooupation”];

Response.Write(“你的職業為:” + cooupation);

%>

在該程序中,使用Request.Form獲取了POST方法所傳遞的數據,從運行結果可以看出,通過POST方法發送的數據不會顯示在URL中,所以,相對來說,使用POST方法發送數據比使用GET方法更安全一些。

Server對象

Server對象提供了對服務器上方法和屬性的訪問。最常用的方法是創建ActiveX組件的實例,其他方法可用于將URL或者HTML編碼成字符串,或者將虛擬路徑映射到物理路徑以及設置腳本的超時時間等。

常用屬性和方法:

1 MachineName

該屬性用于獲取服務器的計算機名稱

2 ScriptTimeout

該屬性用于獲取和設置請求超時時間。例如:將請求超時時間設置為60

Server.ScriptTimeout = 60;

3 HTMLEncode方法

該方法可以對指定的字符串進行HTML編碼。雖然HTML可以顯示大部分寫入到ASP.NET文件中的文本,但是當需要實際包含HTML標記中所使用的字符時,會遇到問題,因為瀏覽器讀到這樣的字符串時會試圖進行解釋。

4 URLEncode方法

該方法可以根據URL規則對字符串進行正確編碼。當字符串數據以URL的形式傳遞到服務器時,在字符串中不允許出現空格,也不允許出現特殊字符。如果希望在發送字符串之前進行URL編碼,可以使用Server對象的URLEncode方法。其語法形式為:

public  string  UrlEncode(string);

public  void  UrlEncode(string, TextWriter);

前一種形式可對給定的字符串進行URL編碼,并返回已編碼的字符串;后一種形式可對給定字符串進行URL編碼,并將結果輸出發送到TextWriter輸出流。

5 MapPath方法

該方法可將指定的相對或者虛擬路徑映射到服務器上相應的物理目錄上。其語法形式為:

public  string  MapPath(string  path);

其中,參數path表示要映射到物理目錄的相對后者虛擬路徑。如果path以符號”/”或者”\”開始,則該方法返回路徑時會將path視為完整的虛擬路徑;如果path不是以斜杠開始的,該方法將返回與頁面文件中已有路徑相對的路徑。另外,MapPath方法并不檢查返回的路徑是否正確,以及是否是服務器上實際存在的路徑

使用Server對象

1 向瀏覽器輸出HTML代碼

使用Server對象的HTMLEncode方法可以向瀏覽器輸出HTML代碼,該方法可以對特殊字符”<””>”進行編碼,當瀏覽器收到經過編碼的字符后會對它們進行解碼,然后把結果顯示出來,因而不會把它們作為HTML標記。

例:

<%

Response.Write(Server.HtmlEncode(“<center><h4>成功屬于,永不放棄的人!<br></h4></center>”));

Resonse.Write(“<center><h4>成功屬于,永不放棄的人!<br></h4></center>”);

%>

運行后,在瀏覽器中分別顯示以下內容:

<center><h4>成功屬于,永不放棄的人!<br></h4></center>

成功屬于,永不放棄的人!

2 創建晚綁定對象

所謂晚綁定對象是指使用Server對象的CreatObject對象創建的對象。例如:

Server.CreageObject(ObjectType);

上述代碼就創建了一個晚綁定對象。使用new語句創建的對象被稱為早綁定對象。使用早綁定對象可以讓編譯器識別錯誤,并具有更好的性能,所以應盡量使用早綁定對象。

Session對象

從一個客戶到達某個網頁開始,到其離開該網頁為止的這段時間內,服務器會為該用戶分配一個Session,以保存該用戶會話時所需要的信息。當客戶在頁面之間切換時,存儲在Session對象中變量不會被清除,當客戶訪問網頁時,這些變量會一直存在;也可以使用Session結束一個會話和設置空閑會話的超時時間。

常用屬性和方法:

1 CodePage

獲取或者設置當前會話的代碼頁標識符

2 Mode

獲取當前會話的狀態模式

3 SessionID

獲取用于標識會話的唯一ID。它可以返回用戶的會話標識符。在傳見會話時,服務器會為每一個會話創建一個標識符,SessionID常常被用于Web頁面注冊統計。

4 Timeout

獲取并設置終止會話之前各請求之間所允許的超時期限(以分鐘為單位)

5 Abandon方法

該方法用于取消當前會話。當Abandon方法被調用時,將會按順序刪除當前的Session對象,只有在當前頁中所有腳本命令都處理完后,對象才會被真正刪除。也可以使用Abandon方法撤銷一個Session

使用Session對象

1 利用Session的自定義屬性保存信息

Session對象的主要用途是保存信息。當一個客戶第一次登陸網站時,系統會為其分配一個Session,只有當該客戶推出時,或者Session的生命周期結束時,信息才會被清除。如下所示,在頁面代碼中添加如下代碼:

<%

Session[“regard”] = “您能光臨本網站,我們感到非常地榮幸!”;

Response.Write(Session[“regard”]);

%>

在該程序中,將一句問候語存儲在Session的自定義屬性Session[“regard”]中,然后將其顯示在網頁上。其實,在給Session[“regard”]賦值以后,不僅可以在當前頁面中讀取它的值,而且可以在其他網頁上讀取它的值。

2 Session的唯一性和Session的終止

當客戶登陸網站后,服務器會為其分配一個Session,不同客戶的Session是各不相同的,用以標識不同的客戶;Session對象的SessionID屬性是用以區別Session的唯一標志,每個Session都具有一個唯一的SessionID

例如,在頁面代碼中添加以下代碼:

<h4>

你好!為您分配的SessionID是:

<% =Session.SessionID %>

</ h4>

為了確定客戶是否已經離開,也就是它所對應的Session應在什么時候結束,需要對Session設置一個超時期限。如果客戶在該期限內沒有對站點的任何頁面提出請求或者刷新頁面,服務器就認為該用戶已經離開,接著就撤銷為其創建的Session。系統默認的Session超時期限為20分鐘,可以通過IIS更改該值,也可以在程序中更改,例如:

Session.Timeout=25;

導航控件

TreeView控件

它的顯示類型類似與一棵橫向的樹,可以展開或折疊樹的節點來分類查看、管理信息,非常直觀。

1 控件的組成元素

TreeView  代表一個TreeView控件實例(根結點)

TreeNode  TreeView中創建一個節點(根的子結點)

TreeNodeType  表示一種TreeNode類型,即一組或者一個節點的樣式

2 控件的部分屬性

ShowExpandCollapse  設置節點折疊時是否顯示”+”標記,該標記表示還可以展開。Showplus設置True表示節點在可折疊時顯示”+”標記,False時則不顯示。

Showlines  節點之間是否使用短線連接,設置為True表示有短線連接各節點。

EnableViewState  設置用戶單擊TreeView控件中的節點時是否觸發提交。

3 控件的主要方法

Add( )方法

Add()方法用于在TreeView樹末尾添加一個TreeNode節點。例:

TreeNode  newTN = new TreeNode( );

newTN.Text = “清華大學出版社”;

newTV.Nodes.Add(newTN);

 

AddAt( )方法

此方法可以在樹的某個特定的位置添加一個節點。例如:添加一個新節點到的一個索引位置的代碼為:

TreeNode  newTN = new TreeNode( );

newTN.Text = “清華大學出版社”;

newTV.Nodes.AddAt(0, newTN);

Add( )方法不同,AddAt( )的第一個參數指定了要添加節點的位置。

 

Remove( )方法

這個方法用來刪除節點及其所有子結點。如果要刪除第一個根節點及其子結點,可用代碼:

TreeNode  delTN = newTV.Nodes[0];

newTV.Nodes.Remove(delTN);

SiteMapPath控件

SiteMapPath控件會顯示一個導航路徑(也稱為當前位置或頁眉導航),此路徑為用戶顯示當前頁的位置,并顯示返回到主頁的路徑鏈接。

使用該控件時要注意:在使用SiteMapPath控件之前,需要添加一個站點地圖文件Web.sitemap只有在該文件中列出的也才能在SiteMapPath控件中顯示導航數據。例如:

<siteMapNode  title=” 主頁  description=”Home”  url=”~/default.aspx”>

        <siteMapNode  title=”服務  description=”Services  we  offer” 

url=”~/Services.aspx”>

        <siteMapNode  title=”培訓  description=”Trainning  classes” 

url=”~/Trainning.aspx” />

        <siteMapNode  title=”查閱  description=”Consulting  services” 

url=”~/Consulting.aspx” />

        </ siteMapNode>

</ siteMapNode>

Menu控件

ASP.NET2.0中的Menu控件使開發人員能夠為經常用于提供導航功能的網頁添加功能。他支持一個主菜單和多個子菜單,并且允許自定義動態菜單。

Menu控件具有兩種顯示模式:靜態模式和動態模式。靜態顯示意味著Menu控件始終是完全展開的。整個結構都是可視的,用戶可以單擊任何部位。在動態顯示的菜單中,只有指定的部分是靜態的,而只有用戶將鼠標指針放置在父節點上時才會顯示其子菜單項。

 

靜態顯示行為:

        使用Menu控件的StaticDisplayLevels屬性可控制靜態顯示行為。StaticDisplayLevels屬性指示從根菜單算起,靜態顯示的菜單的層數。例如,如果將StaticDisplayLevels設置為3,菜單將以靜態顯示的方式展開其前3層。靜態顯示的最小層數為1,如果將該值設置為0或負數,該控件將會引發異常。

 

動態顯示行為:

        MaximumDynamicDisplayLevels屬性指定在靜態顯示層后應顯示的動態顯示菜單節點層數。

常用功能

字符串的處理

1 字符串的連接

ASP.NET中,最常用的就是用”&”來連接兩個字符串

string OurPutString = “My  name  is”;

string InPutString = “Alex”;

string MyOutPutString = OutPutString&InPutString;

2 Insert方法

此方法可以在指定位置插入其他字符,使用方法:

Insert(插入位置,插入字符);

3 Remove方法

此方法可以在指定的位置刪除指定字數的字符,使用方法:

Remove(起始位置,字符數);

4 Replace方法

此方法可以替換指定的字符,使用方法:

Replace(被替換字符串,替換字符串);

5 Trim()

清除字串前後空格

6 字串对比

字串對比一般都用: if(str1==str2){ } , 但還有別的方法:

(1)

string str1; str2

//語法: str1.EndsWith(str2); __檢測字串str1是否以字串str2結尾,返回布林值.:

if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"結束的"); }

(2)

//語法:str1.Equals(str2); __檢測字串str1是否與字串str2相等,返回布林值,用法同上.

(3)

//語法 Equals(str1,str2); __檢測字串str1是否與字串str2相等,返回布林值,用法同上.

7 IndexOf() LastIndexOf()

查找字串中指定字元或字串首次(最後一次)出現的位置,返回索引值,如:

str1.IndexOf("") //查找“字”在str1中的索引值(位置)

str1.IndexOf("字串")//查找“字串”的第一個字元在str1中的索引值(位置)

str1.IndexOf("字串",3,2)//str14個字元起,查找2個字元,查找“字串”的第一個字元在str1中的索引值(位置)

8 PadLeft()PadRight()

在字串左(或右)加空格或指定char字元,使字串達到指定長度,如:

<%

string str1="中國人";

str1=str1.PadLeft(10,'1'); //無第二參數為加空格

Response.Write(str1); //結果為“1111111中國人” 字串長為10

%>

9 為按鈕添加對話框

Button1.Attributes.Add(“onclick”,”return confirm(“確認?”)”);

10 對輸入的Text文本進行HTML字符的過濾。

Shtml = System.Text.RegularExpressions.Regex.Replace(Shtml, "<[^>]*>", "");

DataGrid使用

1 刪除表格選定紀錄

int  intEmpID (int)MyDataGrid.DataKeys[e.Item.ItemIndex];

string deleteCmd = “DELETE  From  Employee  where  emp_id = ” + intEmpID.ToString( );

2 點擊表格行鏈接另一頁

private  void  grd_Customer_ItemDataBind

(object  sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

{

//点击表格打开

if (e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

e.Item.Attributes.Add("onclick","window.open

('Default.aspx?id=" + e.Item.Cells[0].Text + "');");

}

3 雙擊表格鏈接到另一頁

ItemDataBind事件中編寫如下代碼:

if(e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

{

string OrderItemID =e.item.cells[1].Text; 

e.item.Attributes.Add("ondblclick",

"location.href='../ShippedGrid.aspx?id=" + OrderItemID + "'");

}

4 雙擊表格打開新的一頁

if(e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

{

string OrderItemID =e.item.cells[1].Text; 

e.item.Attributes.Add("ondblclick",

"open('../ShippedGrid.aspx?id=" + OrderItemID + "')");

}

特别注意:【?id= 处不能为 ?id =

5 表格超鏈接傳遞參數

<asp:HyperLinkColumn Target="_blank"  headertext="ID" DataTextField="id"
NavigateUrl="aaa.aspx?id='<%# DataBinder.Eval(Container.DataItem, "
数据字段1")%>' & name='<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>' />

6 自定義分頁代碼

先定义变量

public static int pageCount; //总页面数

public static int curPageIndex=1; //当前页面

  下一页:

if(DataGrid1.CurrentPageIndex (DataGrid1.PageCount - 1))

{

 DataGrid1.CurrentPageIndex += 1;

 curPageIndex+=1;

}

bind(); // DataGrid1数据绑定函数

  上一页:

if(DataGrid1.CurrentPageIndex 0)

{

 DataGrid1.CurrentPageIndex += 1;

 curPageIndex-=1;

}

bind(); // DataGrid1数据绑定函数

}

7 直接頁面跳轉

int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值

if(aDataGrid1.PageCount)

{

 this.DataGrid1.CurrentPageIndex=a;

}

8 添加一個編號列

DataTable dt= c.ExecuteRtnTableForAccess(sqltxt); //执行sql返回的DataTable

DataColumn dc=dt.Columns.Add("number",System.Type.GetType("System.String"));

for(int i=0;idt.Rows.Count;i++)

{

 dt.Rows[i]["number"]=(i+1).ToString();

}

DataGrid1.DataSource=dt; //指定數據源為返回的DataTable

DataGrid1.DataBind(); //綁定數據

9 DataGrid1中添加一个CheckBox,页面中添加一个全选框

private void CheckBox2_CheckedChanged(object sender, System.EventArgs e)

{

 foreach(DataGridItem thisitem in DataGrid1.Items)

 {

  ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked;

 }

}

10当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化)

  在Application_Start中添加以下代码:

Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.

   AppSettings["ConnStr"].ToString();

Panel橫向滾動,縱向自動擴展

<asp:panel  style="overflow-x:scroll;overflow-y:auto;"></asp:panel>

格式化

1,將時間格式化

public class MainClass {

    public static void Main(string[] args)  {

        DateTime dt = DateTime.Now;

        String[] format = {

            "d", "D",

            "f", "F",

            "g", "G",

            "m",

            "r",

            "s",

            "t", "T",

            "u", "U",

            "y",

            "dddd, MMMM dd yyyy",

            "ddd, MMM d \"'\"yy",

            "dddd, MMMM dd",

            "M/yy",

            "dd-MM-yy",

        };

        String date;

        for (int i = 0; i < format.Length; i++) {

            date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);

            Console.WriteLine(String.Concat(format[i], " :" , date));

        }

 

   /** Output.

    *

    * d :08/17/2000

    * D :Thursday, August 17, 2000

    * f :Thursday, August 17, 2000 16:32

    * F :Thursday, August 17, 2000 16:32:32

    * g :08/17/2000 16:32

    * G :08/17/2000 16:32:32

    * m :August 17

    * r :Thu, 17 Aug 2000 23:32:32 GMT

    * s :2000-08-17T16:32:32

    * t :16:32

    * T :16:32:32

    * u :2000-08-17 23:32:32Z

    * U :Thursday, August 17, 2000 23:32:32

    * y :August, 2000

    * dddd, MMMM dd yyyy :Thursday, August 17 2000

    * ddd, MMM d "'"yy :Thu, Aug 17 '00

    * dddd, MMMM dd :Thursday, August 17

    * M/yy :8/00

    * dd-MM-yy :17-08-00

    */

    }

}

1 取當前年月日時分秒

currentTime=System.DateTime.Now;

2 取當前年

string  year = DateTime.Now.Year.ToString( );

3 取當前月

string  month = DateTime.Now.Month.ToString( );

4 取當前日

string  day = DateTime.Now.Day.ToString( );

5 取當前時

string  hour = DateTime.Now.Hour.ToString( );

6 取當前分

string  min = DateTime.Now.Minute.ToString( );

7 取當前秒

string  sec = DateTime.Now.Second.ToString( );

8 取中文日期显示——年月日时分

string strY=currentTime.ToString("f"); //不显示秒

9 取中文日期显示_年月

string strYM=currentTime.ToString("y");

10 取中文日期显示_月日

string strMD=currentTime.ToString("m");

11 取中文年月日

string strYMD=currentTime.ToString("D");

'www.knowsky.com

12 取当前时分,格式为:1424

string strT=currentTime.ToString("t");

13 取当前时间,格式为:2003-09-23T14:46:48

string strT=currentTime.ToString("s");

14 取当前时间,格式为:2003-09-23 14:48:30Z

string strT=currentTime.ToString("u");

15 取当前时间,格式为:2003-09-23 14:48

string strT=currentTime.ToString("g");

16 取当前时间,格式为:Tue, 23 Sep 2003 14:52:40 GMT

string strT=currentTime.ToString("r");

17)获得当前时间 n 天后的日期时间

DateTime newDay = DateTime.Now.AddDays(100);

2,變量.ToString( )

字符型转换 转为字符串

112345.ToString("n"); //生成 12,345.00

212345.ToString("C"); //生成 12,345.00

312345.ToString("e"); //生成 1.234500e+004

412345.ToString("f4"); //生成 12345.0000

512345.ToString("x"); //生成 3039 (16进制)

612345.ToString("p"); //生成 1,234,500.00%

3,变量.Substring(参数1,参数2);

截取字串的一部分,参数1为左起始位数,参数2为截取几位。 如:string s1 = str.Substring(0,2);

4,變量.Length

取字串長度:

如: string str="中國";

int Len = str.Length ; //Len是自定義變數, str是求測的字串的變數名

5System.Text.Encoding.Default.GetBytes(變數)

字碼轉換 轉為比特碼

如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);

然後可得到比特長度:

len = bytStr.Length;

6,設置全局變量

  Global.asax

  Application_Start()事件中

  添加Application[属性名] xxx;

  就是你的全局变量

6,大小寫轉換

HttpUtility.HtmlEncode(string);

HttpUtility.HtmlDecode(string)

7,判斷變量是否為數字

  /// <summary>

  /// 名称:IsNumberic

  /// 功能:判断输入的是否是数字

  /// 参数:string oText:源文本

  /// 返回值: bool true:是 false:

  /// </summary>

  public bool IsNumberic(string oText)

  {

   try

   {

    int var1=Convert.ToInt32 (oText);

    return true;

   }

   catch

   {

    return false;

   }

  }

頁面間的操作

1,打開新窗口,并傳遞參數:

传送参数:

response.write("<script>window.open

('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="++"')</script>")

接收参数:

string a = Request.QueryString("id");

string b = Request.QueryString("id1");

2,双击表格连接到另一页

itemDataBind事件中添加如下代碼:

if(e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

{

string OrderItemID =e.item.cells[1].Text;

 

e.item.Attributes.Add("ondblclick",

"location.href='../ShippedGrid.aspx?id=" + OrderItemID + "'");

}

特别注意:【?id= 处不能为 ?id =

3,点击表格行链接另一页

private void grdCustomer_ItemDataBound

(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

{

//点击表格打开

if (e.Item.ItemType == ListItemType.Item ||

e.Item.ItemType == ListItemType.AlternatingItem)

e.Item.Attributes.Add("onclick","window.open

('Default.aspx?id=" + e.Item.Cells[0].Text + "');");

}

4,表格超鏈接傳遞參數

<asp:HyperLinkColumn Target="_blank"  headertext="ID" DataTextField="id"
NavigateUrl="aaa.aspx?id='<%# DataBinder.Eval(Container.DataItem, "
数据字段1")%>'
 & name='<%# DataBinder.Eval(Container.DataItem, "
数据字段2")%>' />

5,獲取錯誤信息并到指定頁面

不要使用Response.Redirect,而应该使用Server.Transfer

e.g

// in global.asax
protected void Application_Error(Object sender, EventArgs e) {
 if (Server.GetLastError() is HttpUnhandledException)
     Server.Transfer("MyErrorPage.aspx");

//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay
}

  Redirect会导致postback的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理

6,子窗體返回主窗體

  ///<summary>

  ///名称:redirect

  ///功能:子窗体返回主窗体

  ///参数:url

  ///返回值:空

  ///</summary>

  public void redirect(string url,Page page)

  {

   if ( Session["IfDefault"]!=(object)"Default")

   {   

    page.RegisterStartupScript("","<script>window.top.document.location.href='"+url+"';</script>");

   }

  }

其他功能

GridView的分頁和排序

asp.net 1.1中,datagrid分頁是很常見的。 而在asp.net 2.0中,依然有兩種分頁方式,一種是默認的分頁方式,比如,有1000條資料,每頁顯示10條資料,則每次頁面請求都必須從資料庫中將1000條資料讀取出來,只不過每次顯示一頁時,顯示10條資料,速度和性能會降低。另一種是自定義分頁方式,比如1000條資料,每頁顯示10條資料,則程式每次在頁面跳轉時,只會從資料庫中拿10條資料出來顯示給用戶,而不是每次都把1000條資料拿出來,因此性能大為提高。

asp.net 2.0中,使用sqldatasource控制項進行分頁是十分容易的事情。Sqldatasource資料源控制項是用來與資料庫打交道的,可以讀取資料庫中的資料,並可以和gridview等控制項進行綁定。在GridView智能標記菜單中選擇"enable paging""enable sorting",即允許分頁和排序,則可以完成分頁和排序的功能了。

而在分頁的效果中,有時我們想讓用戶知道,目前正在流覽的是第幾頁,那麼要如何實現呢?在gridview中,有一個pageindex的屬性,指示頁面的序號(從0開始),則只需在頁面的html代碼內,寫下如下代碼,即可實現效果:

iYou are viewing page

%=productsGridView.PageIndex + 1%

of

%=productsGridView.PageCount%

/i

GridView的常用功能

刪除數據中的某一行

GridView中加入Command列,并選中其中的刪除功能

在后臺定義RowDeleting事件,并在其中添加如下代碼:

string sqlstr="delete from tb_Member where id='"+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";

sqlcon=new SqlConnection(strCon);

sqlcom=new SqlCommand(sqlstr,sqlcon);

sqlcon.Open();

sqlcom.ExecuteNonQuery();

sqlcon.Close();

bind();//綁定GridView與數據庫的函數

編輯數據中的某一行

先在編輯事件中加入如下代碼

protected void GridView_RowEditing(object sender,GridViewEditEventArgs e)

  {

    GridView1.EditIndex=e.NewEditIndex;

    bind();

  }

然后在更新事件中加入如下代碼

protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e)

  {

     sqlcon= new SqlConnection(strCon);

     string sqlstr="update tb_Member set name="

     +((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Control[0])).Text.ToString().Trim()+"',sex='"

     +((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Control[0])).Text.ToString().Trim()+"',nPlace='"

     +((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Control[0])).Text.ToString().Trim()+"',where id='"

     +GridView1.DataKeys[e.RowIndex].Value.ToString()+'";

     sqlcom=new SqlCommand(sqlstr,sqlcon);

     sqlcon.Open();

     sqlcom.ExecuteNonQuery();

     sqlcon.Close();

     GridView1.EditIndex=-1;

     bind();

  }

添加取消按鈕:

protected void GridView1_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)

{

  GridView1.EditIndex=-1;

  bind();

}

GridView控件的模板列中,添加控件,比如DropDownList

首先,將DropDownList控件綁定數據庫代碼如下:

    public SqlDataReader ddlbind()

    {

        string sqlstr = "select distinct City from PaC";

        SqlConnection sqlcon = new SqlConnection("server=(local);user id=sa;pwd=Foxconn88;database=test");

        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);

        sqlcon.Open();

        return sqlcom.ExecuteReader();

    }

其次,編寫頁面登錄代碼,將數據庫與GridView綁定代碼如下

    protected void Page_Load(object sender, EventArgs e)

    {

        DropDownList ddl;

        if (!IsPostBack)

        {

            string sqlstr = "select * from PaC";

            SqlConnection sqlcon = new SqlConnection("server=(local);user id=sa;pwd=Foxconn88;database=test");

            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);

            DataSet myds = new DataSet();

            sqlcon.Open();

            myda.Fill(myds,"PaC");

            GridView1.DataSource = myds;

            GridView1.DataBind();

            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)

            {

                DataRowView mydrv = myds.Tables["PaC"].DefaultView[i];

                if (Convert.ToString(mydrv["City"]).Trim() == "廣州")

                {

                    ddl = (DropDownList)GridView1.Rows[i].FindControl("test");

                    ddl.SelectedIndex = 1;

                }

                if (Convert.ToString(mydrv["City"]).Trim() == "深圳")

                {

                    ddl = (DropDownList)GridView1.Rows[i].FindControl("test");

                    ddl.SelectedIndex = 0;

                }

            }

            sqlcon.Close();

        }

}

GridView控件中實現自動編號

實現代碼如下:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowIndex != -1)

        {

            int id = e.Row.RowIndex + 1;

            e.Row.Cells[0].Text = id.ToString();

        }

    }

Excel中的數據導入到Gridview

重點是將Excel代替數據庫作為數據源,實現代碼如下:

        string path = FileUpload1.PostedFile.FileName;

        string connStr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";

        string sqlStr = "select*from [Sheet1$]";

        OleDbConnection myConn = new OleDbConnection(connStr);

        myConn.Open();

        OleDbCommand myCmd = new OleDbCommand(sqlStr, myConn);

        OleDbDataAdapter myda = new OleDbDataAdapter(myCmd);

        DataSet myDs = new DataSet();

        myda.Fill(myDs, "Sheet1");

        string mystr = "server=(local);uid=sa;pwd=Foxconn88;database=test";

        SqlConnection mySqlConn = new SqlConnection(mystr);

        mySqlConn.Open();

        string strCmd = "";

        int rows = myDs.Tables[0].Rows.Count;

        int cols = myDs.Tables[0].Columns.Count;

        for (int i = 0; i < rows; i++)

        {

            strCmd = "insert into userinfo(userID,userName) values('";

            for (int j = 0; j < cols; j++)

            {

                if (j == 0)

                {

                    strCmd = strCmd + myDs.Tables[0].Rows[i].ItemArray[j].ToString();

                }

                else

                {

                    strCmd += "','" + myDs.Tables[0].Rows[i].ItemArray[j].ToString();

                }

            }

            strCmd += "')";

            SqlCommand mySqlCmd = new SqlCommand(strCmd, mySqlConn);

            Label1.Text = "導入成功";

            mySqlCmd.ExecuteNonQuery();

        }

        bind();

        mySqlConn.Close();

        myConn.Close();

    }

    public void bind()

    {

        string mystr = "server=(local);uid=sa;pwd=Foxconn88;database=test";

        SqlConnection mysqlconn=new SqlConnection(mystr);

        mysqlconn.Open();

        string str = "select * from userinfo";

        SqlCommand com = new SqlCommand(str,mysqlconn);

        SqlDataAdapter da = new SqlDataAdapter(com);

        DataSet ds = new DataSet();

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

        mysqlconn.Close();

    }

}

6,GridView中讀出數據到Excel

先定義點擊導入Excel按鈕時觸發的事件調用的Export方法,代碼如下:

    private void Export(string FileType, string FileName)

    {

        Response.Charset = "GB2312";

        Response.ContentEncoding = System.Text.Encoding.UTF8;

        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());

        Response.ContentType = FileType;

        this.EnableViewState = false;

        StringWriter tw = new StringWriter();

        HtmlTextWriter hw=new HtmlTextWriter(tw);

        GridView1.RenderControl(hw);

        Response.Write(tw.ToString());

        Response.End();

    }

然后在點擊導入Excel按鈕觸發的事件中加入如下代碼:

    protected void Button2_Click(object sender, EventArgs e)

    {

        Export("application/ms-excel", "成績報表.xls");

    }

GridView中讀數據到Excel中,必須重寫VerifyRenderingInServerForm(Control control)方法,代碼如下:

    public override void VerifyRenderingInServerForm(Control control)

    {

        //無須填寫任何代碼

    }

7,在單元格中用”…”替換超長字符

先在bind()方法中添加以下代碼:

        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)

        {

            DataRowView mydrv;

            string gIntro;

            if (GridView1.PageIndex == 0)

            {

                mydrv = ds.Tables["GoodsInfro"].DefaultView[i];

                gIntro = Convert.ToString(mydrv["GoodsIntroduce"]);

                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);

            }

            else

            {

                mydrv = ds.Tables["GoodsInfro"].DefaultView[i+(5*GridView1.PageIndex)];

                gIntro = Convert.ToString(mydrv["GoodsIntroduce"]);

                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);

            }

        }

然后實現其中調用的SubStr方法,代碼如下:

    public string SubStr(string sString, int nLeng)

    {

        if (sString.Length <= nLeng)

        {

            return sString;

        }

        string sNewStr = sString.Substring(0, nLeng);

        sNewStr = sNewStr + "...";

        return sNewStr;

    }

8,將GridView中顯示的學生成績不合格的標記為紅色提醒

代碼如下:

        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)

        {

            DataRowView mydrv = myds.Tables["StuResult"].DefaultView[i];

            string score = Convert.ToString(mydrv["total"]);

            if (Convert.ToInt32(score) < 60)

            {

                GridView1.Rows[i].Cells[5].BackColor = System.Drawing.Color.Red;

            }

        }

9DataGrid行隨鼠標变色

private void DGzf_ItemDataBound
(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
 {
  if (e.Item.ItemType!=ListItemType.Header)
  {
   e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor=
\""+e.Item.style["BACKGROUND-COLOR"]+"\"");
   e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");
  } 
 }

10,讀取控件,如TextBox的值

foreach(DataGrid dgi in yourDataGrid.Items)

{

 TextBox tb = (TextBox)dgi.FindControl("yourTextBoxId");

 tb.Text....

}

11,  datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。

page_load

page.smartNavigation=true

12,  Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小 ?

private void DataGrid1_ItemDataBound(obj sender,DataGridItemEventArgs e)

{

 for(int i=0;ie.Item.Cells.Count-1;i++)

  if(e.Item.ItemType==ListItemType.EditType)

  {

   e.Item.Cells[i].Attributes.Add("Width", "80px")

  }

}

13,  样式交替:

ListItemType itemType = e.Item.ItemType;

if (itemType == ListItemType.Item )

{

 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor=#FFFFFF;";

 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor=#d9ece1;cursor=hand;" ;

}

else if( itemType == ListItemType.AlternatingItem)

{

 e.Item.Attributes["onmouseout"] = "javascript:this.style.backgroundColor=#a0d7c4;";

 e.Item.Attributes["onmouseover"] = "javascript:this.style.backgroundColor=#d9ece1;cursor=hand;" ;

}

14表格点击改变颜色
if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem)
{
  e.Item.Attributes.Add("onclick","this.style.backgroundColor='#99cc00';this.style.color='buttontext';this.style.cursor='default';");

使用嵌套的Repeater控件显示分级数据

  本文描述如何使用嵌套的Repeater 控件来显示分级数据 。当然了,你也可以将这一技术应用到其他的列表绑定控件上去,比如DataGrid包含DataGridDataList包含DataList等等的组合。

  绑定到父表

  1.添加一个新的Web Form 到应用程序项目中,名称为Nestedrepeater.aspx.

  2.从工具箱托动一个Repeater 控件到这个页面上, 设定其ID 属性为 parent .

  3.切换到HTML 视图.

  4.选中下列<itemtemplate 代码,复制到Repeater 控件对应的位置。注意,粘贴的时候请使用“粘贴为html”功能。这些语句包含了数据绑定语法,很简单。

itemtemplate

b><%# DataBinder.Eval(Container.DataItem, "au_id") %></b><br

/itemtemplate

  5.打开Nestedrepeater.aspx.cs 这个代码分离文件。降下列代码添加到Page_Load 事件中,其作用是建立一个到 Pubs (这个数据库是sql server的演示数据库。另外在安装.net framework sdk的时候也会安装这个数据库)数据库的连接,并绑定Authors 表到Repeater 控件

public void Page_Load()

{

 SqlConnection cnn = new SqlConnection("server=(local);database=pubs;uid=sa;pwd=;");

 SqlDataAdapter cmd1 = new SqlDataAdapter("select * from authors",cnn);

  DataSet ds = new DataSet();

  cmd1.Fill(ds,"authors");

  //这里将要插入子表的数据绑定

  parent.DataSource = ds.Tables["authors"];

  Page.DataBind();

 cnn.Close();

  6.在文件的头部添加下面的名称空间

  using System.Data.SqlClient;

  7.根据你自己的情况修改一下连接字符串

  8.保存并编译应用程序

  9.在浏览器中打开这个页面,输出结果类似于下面的格式

172-32-1176

213-46-8915

238-95-7766

267-41-2394

... 

  绑定到子表

  1.在页面的HTML视图中,添加下列代码。其目的是增加子Repeater 控件到父Repeater的项目模板中,形成嵌套。

asp:repeater id="child" runat="server"

itemtemplate

%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]") %><br

/itemtemplate

/asp:repeater

  2.设置子Repeater 控件的DataSource 属性:

asp:repeater ... datasource='%# ((DataRowView)Container.DataItem)

.Row.GetChildRows("myrelation") %'

  3.在页面顶部添加下列指令(请注意,是在.aspx文件中):

  <%@ Import Namespace="System.Data" %

  在.cs文件中,Page_Load中的注释部分(//这里将要插入子表的数据绑定)替换成下列代码:

SqlDataAdapter cmd2 = new SqlDataAdapter("select * from titleauthor",cnn);

cmd2.Fill(ds,"titles");

ds.Relations.Add("myrelation",

ds.Tables["authors"].Columns["au_id"],

ds.Tables["titles"].Columns["au_id"]);

  4.保存并编译应用程序。

  .在浏览器中察看修改后的页面。显示格式类似于下面的格式:

172-32-1176

PS3333

213-46-8915

BU1032

BU2075

238-95-7766

PC1035

267-41-2394

BU1111

TC7777

... 

完整的代码

Nestedrepeater.aspx

%@ Page Language=C# Inherits="yourprojectname.nestedrepeater" %

%@ Import Namespace="System.Data" %

html

body

form runat=server

!-- start parent repeater --

asp:repeater id="parent" runat="server"

  itemtemplate

   <b><%# DataBinder.Eval(Container.DataItem,"au_id") %></b><br

   <!-- start child repeater --

   <asp:repeater id="child" datasource='%# ((DataRowView)Container.DataItem)

.Row.GetChildRows("myrelation") %' runat="server"

    <itemtemplate

      <%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br

     /itemtemplate

   </asp:repeater

   <!-- end child repeater --

 </itemtemplate

/asp:repeater

!-- end parent repeater --

/form

/body

/html

Nestedrepeater.aspx.cs

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace yourprojectname

{

 public class nestedrepeater : System.Web.UI.Page

  {

   protected System.Web.UI.WebControls.Repeater parent;

   public nestedrepeater()

   {

     Page.Init += new System.EventHandler(Page_Init);

   }

   public void Page_Load(object sender, EventArgs e)

   {

     //Create the connection and DataAdapter for the Authors table.

     SqlConnection cnn = new SqlConnection("server=(local);database=pubs;uid=sa;pwd=;");

     SqlDataAdapter cmd1 = new SqlDataAdapter("select * from authors",cnn);

     //Create and fill the DataSet.

     DataSet ds = new DataSet();

     cmd1.Fill(ds,"authors");

     //Create a second DataAdapter for the Titles table.

     SqlDataAdapter cmd2 = new SqlDataAdapter("select * from titleauthor",cnn);

     cmd2.Fill(ds,"titles");

     //Create the relation bewtween the Authors and Titles tables.

     ds.Relations.Add("myrelation",

     ds.Tables["authors"].Columns["au_id"],

     ds.Tables["titles"].Columns["au_id"]);

     //Bind the Authors table to the parent Repeater control, and call DataBind.

     parent.DataSource = ds.Tables["authors"];

     Page.DataBind();

     //Close the connection.

     cnn.Close();

   }

   private void Page_Init(object sender, EventArgs e)

   {

     InitializeComponent();

   }

   private void InitializeComponent()

   {

    this.Load += new System.EventHandler(this.Page_Load);

   }

  }

文件上傳與下載功能

1,上傳功能

 代碼如下

                string path = FileUpload1.FileName;

                string strfilepath = MapPath("testexl") + "\\" + path;

                FileUpload1.PostedFile.SaveAs(strfilepath);

2,固定地址下載功能

 代碼如下

                <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="..\..\Resource\system\ExcelModel\ExcelModel.xls"

                    ForeColor="Blue">導入模板下載</asp:HyperLink>

3,動態地址下載功能

   代碼如下

protected void LinkButton1_Click(object sender, EventArgs e)

    {

        if (Session["txt"] != "")

        {

            string path = Session["txt"].ToString();

            FileInfo fi = new FileInfo(path);

            if (fi.Exists)

            {

                //Response.AddHeader("content-type", "application/x-msdownload");

                Response.AddHeader("Content-Disposition", "attachment;filename=" + fi.Name);

            }

    }

4,设置上传文件的最大大小

web.config中添加httpRuntime元素,如下:

<configuration>

   <system.web>

      <httpRuntime maxRequestLength="8192"

         useFullyQualifiedRedirectUrl="true"

         executionTimeout="45"

         versionHeader="1.1.4128"/>

   </system.web>

</configuration>

其中maxRequestLength属性就是限制上传大小的,如设为"8192"即为8M

5,下载文件关闭窗体之解决方法

对于下载时新打开一窗口下载,下载完后需要关闭的

一种:对于较小文件可以有效:

System.IO.FileInfo file = new System.IO.FileInfo("F:\\mp3\\mp3\\别哭我最爱的人.mp3");

   Response.Clear();

   Response.ClearHeaders();

   Response.Buffer = false;

   Response.Charset="GB2312";

   Response.ContentEncoding=System.Text.Encoding.UTF8;

   Response.ContentType = "application/octet-stream";  

   Response.AddHeader("Content-Disposition", "attachment; filename="+Server.UrlEncode("别哭我最爱的人.mp3"));

   Response.AddHeader("Content-Length", file.Length.ToString());

   Response.WriteFile(file.FullName);

   Response.Flush();

   Response.End();

SqlDataReadDataset的选择

Sqldataread優點:讀取資料非常快。如果對返回的資料不需做大量處理的情況下,建議使用SqlDataReader,其性能要比datset好很多。缺點:直到資料讀完才可close掉於資料庫的連接。

Dataset是把資料讀出,緩存在記憶體中。缺點:對記憶體的佔用較高。如果對返回的資料需做大量的處理用Dataset比較好些。它可以減少對資料庫的連接操作。優點:只需連接一次就可close與資料庫的連接。

ExecuteNonQueryExecuteScalar

對資料的更新不需要返回結果集,建議使用ExecuteNonQuery。由於不返回結果集可省掉網路資料傳輸。它僅僅返回受影響的行數。如果只需更新資料用ExecuteNonQuery性能的開銷比較小。

ExecuteScalar它只返回結果集中第一行的第一列。使用 ExecuteScalar 方法從資料庫中檢索單個值(例如id號)。與使用 ExecuteReader 方法, 返回的資料執行生成單個值所需的操作相比,此操作需要的代碼較少。

*只需更新資料用ExecuteNonQuery.單個值的查詢使用ExecuteScalar資料綁定的選擇。

Session["变量"];

存取Session值;

如,賦值: Session["username"]="小布希";

 

取值: Object objName=Session["username"];

String strName=objName.ToString();

清空: Session.RemoveAll();

QueryString

String str=Request.QueryString["变量"];

用超鏈結傳送變數。

如在任一頁中建超鏈結:<a href=Edit.aspx?fbid=23>点击</a>

Edit.aspx頁中取值:String str=Request.QueryString["fdid"];

char.IsWhiteSpce(字串變數,位元數)--邏輯型

查指定位置是否空字元;

如:

string str="中國 人民";

Response.Write(char.IsWhiteSpace(str,2)); //結果為:True, 第一個字元是0位元,2是第三個字元。

char.IsPunctuation('字元') --邏輯型

查字元是否是標點符號

如:Response.Write(char.IsPunctuation('A')); //返回:False

Math.Max(i,j)

ij中的最大值

int x=Math.Max(5,10); // x將取值 10

FindControl(string id)

這個函數的功能是在目前命名容器搜尋具有指定 id 參數的伺服器控制項。

CSS層疊樣式表

普通控件樣式

添加一個樣式表文件,默認名為StyleSheet.css,在該文件中通過添加如下代碼可實現對每個服務器控件的樣式進行設置的功能。

body{

}

.lab/*文本顯示控件樣式設置*/

{

   font-weght:bold;

   ...

}

.txt/*文本框控件樣式設置*/

{

   font-size:9px;

   ...

}

.button/*按鈕樣式設置*/

{

   font-size:14px;

   ...

}

數據控件樣式

添加一個樣式表文件,默認名為StyleSheet.css,在該文件中通過添加如下代碼可實現對服務器中GridView控件的數據樣式進行設置的功能。

body{

}

.GridView

{

  font-weight:bold;/*文字為粗體*/

  ...

}

頁面樣式

添加一個樣式表文件,默認名為StyleSheet.css,在該文件中通過添加如下代碼可實現對網站整體布局進行設置的功能。

body

{

  font-weight:bold;//字體為粗體

  font-size:9x;//字體大小

  color:#0000;//字體顏色

  font-family:宋體//字體類型

} 

通过使页面动态加载不同CSS实现多界面

%@page language="C#"%

%@import namespace="System.Data"%

script language="c#" runat="server"

public void page_load(Object obj,EventArgs e)

{

//创建服务器端控件.

//指定的标记"LINK"初始化此类的新实例.

HtmlGenericControl objLink=new HtmlGenericControl("LINK");

objLink.ID=ID;

objLink.Attributes["rel"]="stylesheet";

objLink.Attributes["type"]="text/css";

objLink.Attributes["href"]="portal.css";

 

//此控件不产生任何可见输出,仅作为其他控件的容器,可在其中添加,插入或移除控件.

MyCSS.Controls.Add(objLink);

}

/script

html

head

titlec#/title

asp:placeholder id="MyCSS" runat="server"></asp:placeholder

/head

body bgColor="#ffcc66" style="FONT:9pt"

form runat="server"

/form

/body

/html

數據庫操作

1 將文字和图片上传到数据库

<%@ Page Language="C#" EnableViewState="true" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  string strCnn = "Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);";

  protected void Button1_Click( object sender, EventArgs e )

  {

    System.IO.Stream fileDataStream = FileUpload1.PostedFile.InputStream;

    if (fileDataStream.Length < 1)

    {

      Msg.Text = "请选择文件。";

      return;

    }

    //得到文件大小

    int fileLength = FileUpload1.PostedFile.ContentLength;

    //创建数组

    byte[] fileData = new byte[fileLength];

    //把文件流填充到数组

    fileDataStream.Read(fileData, 0, fileLength);

    //得到文件类型

    string fileType = FileUpload1.PostedFile.ContentType;

    //构建数据库连接,SQL语句,创建参数

    SqlConnection myConnection = new SqlConnection(strCnn);

    SqlCommand command = new SqlCommand("INSERT INTO UserPhoto (UserName,ContentType,Photo)" +

    "VALUES (@UserName,@ContentType,@Photo)", myConnection);

    command.Parameters.AddWithValue("@UserName", TextBox1.Text);

    command.Parameters.AddWithValue("@ContentType", fileType);

    command.Parameters.AddWithValue("@Photo", fileData);

    //打开连接,执行查询

    myConnection.Open();

    command.ExecuteNonQuery();

    myConnection.Close();

    Response.Redirect(Request.RawUrl);

  }

  protected void Page_Load( object sender, EventArgs e )

  {

    if (!Page.IsPostBack)

    {

      BindGrid();

    }

  }

  private void BindGrid( )

  {

    SqlConnection myConnection = new SqlConnection(strCnn);

    SqlCommand myCommand = new SqlCommand("SELECT * FROM UserPhoto Order By id DESC", myConnection);

    try

    {

      myConnection.Open();

      GridView1.DataSource = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

      GridView1.DataBind();

    }

    catch (Exception SQLexc)

    {

      Response.Write("提取数据时出现错误:" + SQLexc.ToString());

    }

  }

  protected string FormatURL( object strArgument )

  {

    return "ReadImage.aspx?id=" + strArgument.ToString();

  } 

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

  <title>上传文件到数据库</title>

</head>

<body>

  <form id="MengXianhui" runat="server">

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

      <Columns>

        <asp:TemplateField>

          <ItemTemplate>

            <%#Eval("UserName") %>

          </ItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField>

          <ItemTemplate>

            <img src="<%#FormatURL(Eval("id")) %>" /></ItemTemplate>

        </asp:TemplateField>

      </Columns>

    </asp:GridView>

    <br />

    <br />

    姓名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <br />

    照片:<asp:FileUpload ID="FileUpload1" runat="server" />

    <asp:Button ID="btnUpload" runat="server" Text="上传" OnClick="Button1_Click"></asp:Button>

    <p>

      <asp:Label ID="Msg" runat="server" ForeColor="Red"></asp:Label></p>

  </form>

</body>

</html>

显示图片

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data.OleDb" %>

<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

  protected void Page_Load( object sender, EventArgs e )

  {

    ////构建数据库连接,SQL语句,创建参数

    //ACCESS数据库使用本注释部分

    //string strCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Image2Access.mdb");

    //OleDbConnection myConnection = new OleDbConnection(strCnn);

    //OleDbCommand command = new OleDbCommand("select * from Person Where PersonID =" + Request.QueryString["id"], myConnection);

    //myConnection.Open();

    //OleDbDataReader dr = command.ExecuteReader();

    //if (dr.Read())

    //{

    //  Response.Clear();

    //  Response.AddHeader("Content-Type", dr["PersonImageType"].ToString());

    //  Response.BinaryWrite((byte[])dr["PersonImage"]);

    //}

    //dr.Close();

    //myConnection.Dispose();

    //构建数据库连接,SQL语句,创建参数

    string strCnn = "Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);";

    SqlConnection myConnection = new SqlConnection(strCnn);

    SqlCommand command = new SqlCommand("select * from UserPhoto Where id =" + Request.QueryString["id"], myConnection);

    myConnection.Open();

    SqlDataReader dr = command.ExecuteReader();

    if (dr.Read())

    {

      Response.Clear();

      Response.AddHeader("Content-Type", dr["ContentType"].ToString());

      Response.BinaryWrite((byte[])dr["Photo"]);

    }

    dr.Close();

    myConnection.Dispose();

  }

</script>

创建SQL数据表语句

CREATE TABLE [UserPhoto] (

        [id] [int] IDENTITY (1, 1) NOT NULL ,

        [UserName] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NOT NULL ,

        [ContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,

        [Photo] [image] NOT NULL ,

        CONSTRAINT [PK_UserPhoto] PRIMARY KEY  CLUSTERED

        (

                [id]

        )  ON [PRIMARY]

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

讀取數據庫中一定長度的文字作為摘要

GridView中加入如下模板列:

            <asp:TemplateField FooterText="學習內容" HeaderText="學習內容">

                <ItemTemplate>                   

                    <a href='./newDailyReport.aspx?no=<%#DataBinder.Eval(Container.DataItem, "DID")%>'>

                    <%# DataBinder.Eval(Container.DataItem, "StudyContent").ToString().Substring(0,3) + "..."%></a>

                </ItemTemplate>

                <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />

            </asp:TemplateField>

posted on 2008-09-08 10:15  螞蟻漫步  阅读(2356)  评论(0编辑  收藏  举报