在設計管理頁面像是文章、資料管理清單等等

都可以藉由.net套件GridView來達成

而內建的GridView在坊間又有很多書來介紹這東西

但是有些入門書都同樣提到了使用智慧標籤精靈來達成

作法是先設定sqldatasource的connectionString並且把連接字串給了GridView

有點像是之前所提到的[ASP]用智慧標籤來完成你的資料連結

VS就會藉由BoundField這樣的標籤將資料庫所擁有的欄位給Bind且自動產生Table

這樣做起來的確是快速又方便!

但如果今天要修改一些較細微地內容時,精靈相對沒這麼有彈性


 以下自訂一個GridView 並連接起來

環境: VS2012

資料庫: SQL Server 2008

 

事前準備:

要有資料庫的內容提供作為Bind

Table部分

CREATE TABLE candidate(
No Int,
Name Nvarchar(max),
Address Nvarchar(max)
)

Data部分

INSERT INTO candidate VALUES(1,'TOM','Taiwan');
INSERT INTO candidate VALUES(2,'Kally','USA');
INSERT INTO candidate VALUES(3,'John','UK');
INSERT INTO candidate VALUES(4,'Stanley','Japan');

  

1.新增一個GridView

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    </div>
</form>


2.在此藉由GridView預設的屬性AutoGenerateColumns=true可以產生出GridView資料欄位

3.首先撰寫方法去撈取資料

這邊使用C#來與SQL SERVER做連接,先加入參考!

private DataSet getData()
    {
        String connectString = "Data Source=localhost;database=Test; Integrated Security=SSPI;";
        SqlConnection cn = new SqlConnection(connectString);
        String selectString = "SELECT * FROM candidate";
        SqlCommand cmd = new SqlCommand(selectString, cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        cn.Open();
        da.Fill(ds);
        cn.Close();
        return ds;
    }

4.藉由呼叫getData()回傳的DataSet放入GridView的Source

 private void GVgetData()
    {
        GridView1.DataSource = getData();
        GridView1.DataBind();
    }

5.在來就是在網頁Load同時呼叫GVgetData()的方法,記得加入Page.IsPostBack的條件判斷,以避免在GridView.Bind()時,對頁面重新產生所造成的錯誤

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            GVgetData();
    }

 

 

以上為自己在自訂的時候的筆記,有任何問題歡迎討論指教

arrow
arrow
    全站熱搜

    chuangmaster 發表在 痞客邦 留言(0) 人氣()