zoukankan      html  css  js  c++  java
  • ADO.NET #3-1 (GridView + DataReader + SqlCommand)完全手写Code Behind

    之前有分享过一个范例

    [C#] ADO.NET #3 (GridView + SqlDataSource)完全手写、后置程序代码,兼论 SqlDataSource与UpdateParameter/DeleteParameter的用法

    后来,在网络上找到的人,就开始大量地为「SqlDataSource小精灵」动手写程序

    这并非我的原意。

    我的意思是,透过手写的程序代码,让您知道 SqlDataSource「骨子里面」也是ADO.NET

    但,网络上乱找范例,抄了就上.....这样的心态,我也帮不上忙。

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

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

    前两天,有位读者询问「上集第十章的范例, 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)

    这三个主题要讲一整天的课

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

    对应的课程如下:

    这也是七周课程里面的「第三天&第四天」重点!!

    远距教学-- 大型控件完全解密+ADO.NET实战范例 (14hr)

     

    相关文章&范例:

    [习题]上集 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 --
     
  • 相关阅读:
    Linuxday4——文件管理
    LinuxDay9——文件查找和压缩
    LinuxDay1——计算机基础
    LinuxDay2——Linux历史
    LinuxDay5——标准I/O和管道
    加入园子一周年
    终于把Blog地址改为Random.cnblogs.com了
    写了个文件上传操作的类
    [照片]尖山行
    C#命名约定[转]
  • 原文地址:https://www.cnblogs.com/mis2000lab/p/5067393.html
Copyright © 2011-2022 走看看