[C#] ADO.NET #3-1 (GridView + DataReader + SqlCommand)完全手寫、後置程式碼

摘要:[C#] ADO.NET #3-1 (GridView + DataReader + SqlCommand)完全手寫、後置程式碼

包含 YouTube教學影片

 

之前有分享過一個範例

[C#] ADO.NET #3 (GridView + SqlDataSource)完全手寫、後置程式碼,兼論 SqlDataSource與UpdateParameter/DeleteParameter的用法

 

後來,在網路上找到的人,就開始大量地為「SqlDataSource小精靈」動手寫程式

這並非我的原意。

我的意思是,透過手寫的程式碼,讓您知道 SqlDataSource「骨子裡面」也是ADO.NET

 

但,網路上亂找範例,抄了就上.....這樣的心態,我也幫不上忙。

https://www.youtube.com/watch?v=tnGqKV4F_Pk

 

 ................................................................................................................

本範例的執行成果,為什麼要自己動手寫這些功能?

學會了可以得到什麼???請看我在YouTube錄製的影片 -- https://youtu.be/KFQvhiQcz1U

 

前兩天,有位讀者詢問「上集第十章的範例, GridView一次只能編輯(更改)、刪除一筆記錄,為何要用DataSet來做??」

因為.......我拿這個範例來 Demo DataSet的刪除、分頁、更新等等功能

不是「只能」這樣做  Orz

 

所以,我把這個範例(ASP.NET專題實務 / 博碩出版。上集,第十章)

改用 SqlCommand + DataReader來做。

 

首先,畫面上只有一個簡單的 GridView

<asp:GridView ID="GridView1" runat="server"  PageSize="5" DataKeyNames="id"

            OnRowCancelingEdit="GridView1_RowCancelingEdit"

            OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"

            OnRowUpdating="GridView1_RowUpdating">

            <Columns>

                <asp:CommandField ButtonType="Button" ShowEditButton="True" />

                <asp:CommandField ShowSelectButton="True" />

                <asp:CommandField ShowDeleteButton="True" />

            </Columns>

        </asp:GridView>

 

 

後置程式碼:

using System.Web.Configuration;

using System.Data.SqlClient;

using System.Data;

    protected void DBInit()   //====自己手寫的程式碼, Datareader / SqlCommand ====(Start)

    {  

           // 透過 DataReader 來做分頁,以前已經發表過了。

           // 請看下面文章& Youtube影片教學: 

[.NET 4.5]GridView自訂分頁的新屬性,AllowCustomPaging與 VirtualItemCount #2 範例 - DataReader +資料庫分頁

    }

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)     {

            DBInit();   //---只有[第一次]執行本程式,才會進入 if判別式內部。

            // 第一次執行本程式,請從「GridView 第一頁(0)」看起。

        }

    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {   //----修改、更新

        //----因為前面有三個「功能鍵(編輯、選取、刪除)」,所以Cells[ ]從零算起,需扣掉前三個功能鍵與 id欄位。

        TextBox my_test_time, my_title, my_author;

        my_test_time = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];   // 抓到「Text控制項」。

        my_title = (TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0];

        my_author = (TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0];

        //=== DataReader的寫法 ==========================================

        SqlConnection Conn = new SqlConnection("您自己的連結字串,或是Web.Config裡面的連結字串");

        Conn.Open();  

        

        //== (2). 執行SQL指令。或是查詢、撈取資料。

        SqlCommand cmd = new SqlCommand("update [test] set [test_time] = @test_time, [title] = @title, [author] = @author where [id] = @id", Conn);

        cmd.Parameters.AddWithValue("@test_time", Convert.ToDateTime(my_test_time.Text));

        cmd.Parameters.AddWithValue("@title", my_title.Text);

        cmd.Parameters.AddWithValue("@author", my_author.Text);

        cmd.Parameters.AddWithValue("@id", (int)GridView1.DataKeys[e.RowIndex].Value);

        //---- GridView1.DataKeys[e.RowIndex].Value 是指:「使用者點選的那一列」資料,所對應的資料表「主索引鍵(Primary Key)值」。

        //== (3). 自由發揮。

        int RecordsAffected = cmd.ExecuteNonQuery();

        //Response.Write("執行 Update的SQL指令以後,影響了" + RecordsAffected + "列的紀錄。)";

        //== (4). 釋放資源、關閉資料庫的連結。

        cmd.Cancel();

        if (Conn.State == ConnectionState.Open)   {

            Conn.Close();

            Conn.Dispose(); 

        }

        //==========================================================

        //----修改、更新完成!!離開「編輯」模式  ----

        GridView1.EditIndex = -1;

        DBInit();

    }

    //==============================================

    //== GridView的分頁,無法搭配 DataReader。所以要自己寫分頁!

    //protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    //{   //----分頁 Start----

    //    GridView1.PageIndex = e.NewPageIndex;

    //    DBInit();

    //}

    //==============================================

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {   //----編輯模式----

        GridView1.EditIndex = e.NewEditIndex;

        DBInit();

        //----畫面上的GridView,已經事先設定好「DataKeyName」屬性 = id ----

        //----所以編輯時,主索引鍵id 欄位會自動變成「唯讀」----

    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {   //---離開「編輯」模式----

        GridView1.EditIndex = -1;

        DBInit();

    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {   //----刪除一筆資料

        //=== DataReader的寫法 ==========================================

        SqlConnection Conn = new SqlConnection("您自己的連結字串,或是Web.Config裡面的連結字串");

        Conn.Open();   //---- 這時候才連結DB

        //== (2). 執行SQL指令。

        SqlCommand cmd = new SqlCommand("delete from [test] where [id] = @id", Conn);

        cmd.Parameters.AddWithValue("@id",(int)GridView1.DataKeys[e.RowIndex].Value);

        //== (3). 自由發揮。

        int RecordsAffected = cmd.ExecuteNonQuery();

        //== (4). 釋放資源、關閉資料庫的連結。

        cmd.Cancel();

        if (Conn.State == ConnectionState.Open)

        {

            Conn.Close();

            Conn.Dispose(); 

        }

        //==========================================================

        //----「刪除」已經完成!!記得重新整理畫面,重新載入資料----

        DBInit();

    }

 

這個範例的程式碼看來雖然多又雜

但拆解開來,不過是三大主題:

  • 大型控制項的 CommandField & 對應的事件(事件裡面的 e,是什麼意思?)
  • .FindControl()方法與 .Controls
  • ADO.NET ( DataReader + DataSet / DataTable)

 

這三個主題要講一整天的課

所以初學者看不懂,才是「正常的」!因為有很多學問要先搞懂。

 

對應的課程如下:

這也是七週課程裡面的「第三天&第四天」重點!![遠距教學、教學影片] ASP.NET (Web Form) 課程上線!MIS2000Lab.主講

          https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

 

相關文章&範例:

[習題]上集 Ch 14-4 (Repeater與 ListView版) -- 撰寫ADO.NET DataReader的分頁程式#2(搭配SQL指令 ROW_NUMBER)

[習題]上集 Ch 14-4 撰寫ADO.NET DataReader的分頁程式#3(搭配SQL 2012指令 OFFSET...FETCH)

[讀書心得]資料分頁的最佳化,以SQL 2012的 OFFSET-FETCH為例

 

 

[習題]上集 Ch 14-4 (Repeater與 ListView版) -- 撰寫ADO.NET DataReader的分頁程式#2(搭配SQL指令 ROW_NUMBER)

 

GridView自訂分頁樣式#1(以下拉式選單,DropDownList做分頁)與分頁樣版(PagerTemplate)-- TopPagerRow與 BottomPagerRow屬性

https://www.youtube.com/watch?v=oY7jd0ABXeM

 ................................................................................................................

這位外國朋友每一篇文章與範例,都貼心地附上 YouTube影片教學,實在令人佩服

推薦給大家。

相同範例,他改用 EF 來做 GridView CRUD --

How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET Webforms application

(1) http://dotnetawesome.blogspot.com/2015/04/how-to-implement-basic-crud-functionality-entity-framework-aspnet-webforms.html

(2) http://dotnetawesome.blogspot.com/2015/04/part-2-how-to-implement-basic-crud-functionality-entity-framework-aspnet-webforms.html

 

 

 

我將思想傳授他人, 他人之所得,亦無損於我之所有;

猶如一人以我的燭火點燭,光亮與他同在,我卻不因此身處黑暗。----Thomas Jefferson

線上課程教學,遠距教學 (Web Form 約 51hr)  https://dotblogs.com.tw/mis2000lab/2016/02/01/aspnet_online_learning_distance_education_VS2015

線上課程教學,遠距教學 (ASP.NET MVC 約 135hr)  https://dotblogs.com.tw/mis2000lab/2018/08/14/ASPnet_MVC_Online_Learning_MIS2000Lab

 

寫信給我,不要私訊 --  mis2000lab (at) yahoo.com.tw  或  school (at) mis2000lab.net

 (1) 第一天 ASP.NET MVC5 完整影片(5.5小時 / .NET 4.x版)免費試聽。影片 https://youtu.be/9spaHik87-A 

 (2) 第一天 ASP.NET Core MVC 完整影片(3小時 / .NET Core 6.0~8.0)免費試聽。影片 https://youtu.be/TSmwpT-Bx4I 

[學員感言] mis2000lab課程評價 - ASP.NET MVC , WebForm  。 https://mis2000lab.medium.com/%E5%AD%B8%E5%93%A1%E6%84%9F%E8%A8%80-mis2000lab%E8%AA%B2%E7%A8%8B%E8%A9%95%E5%83%B9-asp-net-mvc-webform-77903ce9680b  


ASP.NET遠距教學、線上課程(Web Form + MVC)。 第一天課程, "完整" 試聽。 

.........   facebook社團   https://www.facebook.com/mis2000lab   ......................

.........  YouTube (ASP.NET) 線上教學影片  https://www.youtube.com/channel/UC6IPPf6tvsNG8zX3u1LddvA/

 

Blog文章 "附的範例" 無法下載,請看 https://dotblogs.com.tw/mis2000lab/2016/03/14/2008_2015_mis2000lab_sample_download

請看我們的「售後服務」範圍(嚴格認定)。

...................................................................................................................................................... 

ASP.NET MVC  => .NET Core MVC 線上教學  ...... 第一天課程 完整內容 "免費"讓您評估 / 試聽

[遠距教學、教學影片] ASP.NET (Web Form) 課程 上線了!MIS2000Lab.主講   事先錄好的影片,並非上課側錄!   觀看時,有如「一對一」面對面講課