ADO #3-1 (GridView + DataReader + SqlCommand) fully handwritten code Behind

Source: Internet
Author: User

[C #] ADO #3-1 (GridView + DataReader + SqlCommand) fully handwritten, post-program code

Have shared an example before

[C #] ADO #3 (GridView + SqlDataSource) fully handwritten, post-program code, and the use of SqlDataSource and Updateparameter/deleteparameter

Later, on the network to find people, began a lot of for the "sqldatasource elf" write program

It's not my intention.

I mean, through the handwriting code, let you know sqldatasource"bones" is also ADO

But, on the Internet to find examples, copied on the ... Such a mentality, I can not help.

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

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

Two days ago, a reader asked "last episode the example of the tenth chapter, the GridView can only edit (change), delete a record, why use a dataset to do??" 」

Because....... I take this example to Demo the dataset Delete, paging, update and so on functions

and not "only" do it Orz

So, I'm publishing this example (ASP./Songgang). Last episode, tenth chapter)

Instead, use SqlCommand + DataReader to do it.

First, there's only one simple GridView on the screen.

<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"/&            Gt </Columns> </asp:GridView>

Post-Program code:

Using system.web.configuration;using system.data.sqlclient;using System.Data; protected void DBInit ()//==== own handwritten program code, Datareader/sqlcommand = = (Start){ //through DataReader to make pagination, has been published before. //See the following article on YouTube video tutorial:[. NET 4.5] GridView Custom Paging new properties, allowcustompaging and VirtualItemCount #2 Example-DataReader + database paging} protected void Page_Load(object sender, EventArgs e) {if (! Page.IsPostBack) {DBInit ();//---Only the [first] execution of this procedure will enter the if discriminant inside. //For the first time, please look at the first page of "gridview (0). }} protected void gridview1_ RowUpdating(object sender, Gridviewupdateeventargs e) { //----modification, update//----because there are three "function keys (edit, select, delete)", cells[] from zero, you need to deduct the first three function keys and ID fields. TextBox My_test_time, My_title, My_author; My_test_time = (TextBox) Gridview1.rows[e.rowindex]. CELLS[4]. Controls[0];//Catch "text control". 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 ("Your own link string, or the link string inside the Web. config"); Conn.Open ();        //== (2). Execute the SQL directive. or query and skim data. SqlCommand cmd = new SqlCommand ("Update [test] set [test_time] = @test_time, [title] = @title, [author] = @author WHERE [i        D] = @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 refers to the "user-selected column" data, which corresponds to the data table "PRIMARY key (Primary key) value". //== (3). Free to play. int RecordsAffected = cmd. ExecuteNonQuery ();//response.write ("After executing the SQL instruction for update, the record of the" + RecordsAffected + "column is affected.) )";//== (4). Release the resource and close the link to the database. Cmd.         Cancel ();            if (conn.state = = ConnectionState.Open) {conn.close ();         Conn.dispose (); }        //==========================================================//----modification, UPDATE complete!! Leave edit mode----Gridview1.editindex =-1;    DBInit (); }    //==============================================//== The page of the GridView, unable to match the DataReader. So you have to write your own pagination! //protected void gridview1_pageindexchanging(object sender, Gridviewpageeventargs e)//{//----page Start----//Gridview1.pageindex = E.newpageindex;//DBInit ();    //}    //==============================================protected void gridview1_ RowEditing(object sender, GridViewEditEventArgs e) {//----edit mode----Gridview1.editindex = E.neweditindex; DBInit ();//----The GridView on the screen, the "datakeyname" attribute = ID has been set beforehand----//----So when editing, the primary key ID field automatically becomes "read-only"----} protected void Gridview1_ Rowcancelingedit(object sender, Gridviewcancelediteventargs e) {//---Leave edit mode----Gridview1.editindex =-1;    DBInit (); } protected void Gridview1_ rowdeleting(object sender, Gridviewdeleteeventargs e) {//----Delete a piece of data//=== DataReader ==========================================SqlConnection Conn = new SqlConnection ("Your own link string, or the link string inside the Web. config"); Conn.Open ();//----Connect db at this time//== (2). Execute the SQL directive. SqlCommand cmd = new SqlCommand ("Delete from [test] where [id] = @id", Conn); Cmd. Parameters.addwithvalue ("@id", (int) Gridview1.datakeys[e.rowindex]. Value);//== (3). Free to play. int RecordsAffected = cmd. ExecuteNonQuery ();//== (4). Release the resource and close the link to the database. Cmd.        Cancel ();            if (conn.state = = ConnectionState.Open) {conn.close ();         Conn.dispose (); }        //========================================================== //----"Delete" has been completed!! Remember to re-organize the screen, reload the data----DBInit (); }

The program code for this example seems to be a lot more miscellaneous

But dismantling is just three main themes:

    • CommandField of large controls & corresponding events (E in the event, what does that mean?) )
    • . FindControl () method and. Controls
    • ADO (DataReader + dataset/datatable)

These three subjects have a whole day of lessons to be told.

So beginners can not understand, is the "normal"! Because there is a lot of learning to understand first.

The corresponding courses are as follows:

This is also the "Third day and fourth day" focus in the seven week course!!

Distance teaching-Large control completely decrypts +ado. NET combat paradigm (14HR)

Related Articles & Examples:

[Exercise] Last episode Ch 14-4 (Repeater and ListView Edition)--writing the paging Program for ADO DataReader (with sql command Row_number)

[Exercise] Last episode Ch 14-4 write the page of the DataReader ADO # # # (with SQL 2012 instruction OFFSET ...) FETCH)

[Reading experience] optimization of data paging, taking offset-fetch of SQL 2012 as an example

[Exercise] Last episode Ch 14-4 (Repeater and ListView Edition)--write the page Program of ADO DataReader (with sql command Row_number) GridView custom page Style # # (The following pull-down menu, DropDownList pagination) and page-like (pagertemplate)-Toppagerrow and Bottompagerrow properties

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

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

This foreign friend, every article and example, is attached to the YouTube film teaching, it is really admirablerecommend to everyone. the same paradigm, he switched to EF to do the 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

ADO #3-1 (GridView + DataReader + SqlCommand) fully handwritten code Behind

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.