Use Visual C # to modify and delete database records

xiaoxiao2021-03-06  39

In the previous article "

Visual C # easy to browse database records in Visual C #

"In, we introduced how to use Visual C # to bind the field values ​​in the data table to the properties of the text box and how to operate the data log pointer, and browse the records in the data table. This article will then describe the content of Visual C # to modify and delete data records.

I. Environmental settings for programming and running:

Window 2000 Server Edition Microsoft Access Data Component 2.6 or above (MADC 2.6) This article describes the database used by this program: For convenience, the local database Access 2000 is selected in the selection database, of course, you can also use other types of databases, just need Change the engine of the database in the source code behind the article and change the corresponding code. The database name used in this program is sample.mdb, and there is a data table books in this database. The structure of this data sheet is as follows:

Field Name Field Type Represents Bookid Digital Serial Number BookTitle Text Book Name Book AppRICE Digital Price Bookstock Digital Book Number

II. Problems for programming difficulties and should pay attention to:

The key points and difficulties in programming are how to delete records and how to modify records in Visual C #. The following is the necessary discussion on these two issues:

How to correctly remove records in the data table in Visual C #: Note when using Visual C # Remove records: You must completely delete records from two aspects, ie, from a database and a DataSet object generated when programming with Visual C #, thoroughly delete. When the program is designed, if only the record information in the DataSet object is deleted, this deletion is a pseudo-deduplication. This is because when he exits the program, re-run the program, it will find that the record to be deleted still exists. This is because the DataSet object is just a mirroring of the data table, not the real record itself. However, if the record is deleted from the database, because the data set for the program is read from the DataSet object, the image recorded in the sub-DataSet object is still saved. So it will find that we have not deleted records at all, but it has been deleted. At this point, only the exit program is re-run, and the record has been deleted. The method used herein is to delete records or record mirror information in the above two aspects. Of course, you can also use other methods, such as: First remove the records from the database, and re-create a data connection, recreate a new DataSet object. This method can also achieve the same purpose, but it is obviously relatively complicated, so this paper is the first method - directly delete. The specific implementation statements in the program are as follows:

// Connect to a database string strcon = "provider = microsoft.jet.OLEDb.4.0; data source = sample.mdb"; oledbconnection myconn = new oledbconnection (strcon); myconn.open (); string strde = "delete from books WHERE BOOKID = " T_bookid.text; OLEDBCommand MyCommand = New OLEDBCOMMAND (STRDELE, MyConn); // Remove the specified record in the database MyCommand.executenonQuery (); // Remove the specified record information from DataSet MyDataSet.Tables [" Books " ]. Rows [mybind.position]. Delete (); mydataset.tables ["books"]. Acceptchange (); myconn.close (); use Visual C # to modify the record in the data table: Modify the record with Visual C # Delete records, which are substantially different in programming, and specific implementations are also implemented by SQL statement calls. Here is the specific statement of the record in the program: // Connect to a database string strcon = "provider = microsoft.jet.OleDb.4.0; data source = sample.mdb"; OLEDBConnection myconn = new oledbconnection (strcon); MyConn. Open (); // Modify the specified record from the database string strupdt = "Update books set booktitle = '" t_booktitle.text ", BookAuthor ='" t_bookauthor.text "', BookPrice =" T_BookPrice.Text ", bookstock =" t_bookstock.Text "WHERE bookid =" t_bookid.Text; OleDbCommand myCommand = new OleDbCommand (strUpdt, myConn); myCommand.ExecuteNonQuery (); myConn.Close (); understand how to use Visual C # After deleting and modifying the record, combined with the contents of "easy to browse the database record in Visual C #, you can get the comparison full program code with Visual C # complete the deletion and modify the data record. Here is the operation of this article. Program interface:

Click on the small picture to enlarge, the interface after running the program in this article

3. Implement the full source code code for deleting and modifying database records with Visual C #:

using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Data.OleDb; using System.Data; public class DataEdit: Form {private System.ComponentModel.Container components; private Button delete; private Button update; private Button lastrec; private Button nextrec; private Button previousrec; private Button firstrec; private TextBox t_bookstock; private TextBox t_bookprice; private TextBox t_bookauthor; private TextBox t_booktitle; private TextBox t_bookid; private Label l_bookstock; private Label l_bookprice; private Label l_bookauthor; private Label l_booktitle; private Label l_bookid; private Label label1; private System.Data.DataSet myDataSet; private BindingManagerBase myBind; private bool isBound = false; // this variable is defined, is to determine whether binding component data field in a table Public DataEdit () {// InitializeComponent (); // Connect to a database getConnected ();} // Clear all Resources used in the program PUBLIC OVERRIDE VOID DISPOSE () {base .Dispose (); Components.Dispose (); PUBLIC VOID GETCONNEC ted () {try {// Create an OleDbConnection object string strCon = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = sample.mdb"; OleDbConnection myConn = new OleDbConnection (strCon); string strCom = "SELECT * FROM Books "; // Create a DataSet object myDataSet = new dataset (); myconn.open (); oledbdataadapter mycommand = new oledbdataadapter (strcommand.fill (MyDataSet," Books "); myconn.close (); myconn.close (); // Determine if the data field is bound to textboxesif (! Isbound) {// The following is to display a field of the data table to a different binding to the text box "text" attribute on t_bookid.DataBindings. Add ("text", mydataset, "books.bookid"); t_booktitle.databindings.add ("text", mydataset, "books.booktitle");

t_bookauthor.DataBindings.Add ( "Text", myDataSet, "books.bookauthor"); t_bookprice.DataBindings.Add ( "Text", myDataSet, "books.bookprice"); t_bookstock.DataBindings.Add ( "Text", myDataSet, "Books.bookStock"); // Set BindingManagerBase // Bind the object Dataset and "Books" data sheet to this Mybind object mybind = this.bindingContext [myDataSet, "Books"]; isbound = true;}} catch Exception E) {MessageBox.show ("Connection database error is:" E.toTRING (), "Error!");}} Public static void main ()} public static void main ();} private (); void InitializeComponent () {this.components = new System.ComponentModel.Container (); this.t_bookid = new TextBox (); this.previousrec = new Button (); this.l_bookauthor = new Label (); this.delete = new Button (); this.t_booktitle = new TextBox (); this.t_bookauthor = new TextBox (); this.t_bookprice = new TextBox (); this.l_bookprice = new Label (); this.t_bookstock = new TextBox (); this .l_bookstock = new label (); this.l_booktitle = new label (); this.Update = new but Ton (); this.nexTrec = new button (); this.lastrec = new button (); this.firstrec = new button (); this.label1 = new label (); THISL_BOOKID = new label (); t_bookid .Location = new system.drawing.point (184, 56); t_bookid.size = new system.drawing.size (80, 20); t_booktitle.location = new system.drawing.point (184, 108); t_booktitle.size = new system.drawing.size (176, 20); t_bookauthor.location = new system.drawing.point (184, 160); t_bookauthor.size = new system.drawing.size (128, 20); t_bookprice.location =

new System.Drawing.Point (184, 212); t_bookprice.Size = new System.Drawing.Size (80, 20); t_bookstock.Location = new System.Drawing.Point (184, 264); t_bookstock.Size = new System .Drawing.size (80, 20); // The following is the label property L_bookId.Location = new system.drawing.point (24, 56); l_bookid.text = "sequence number: l_bookid) .Size = new System.Drawing.Size (142, 20); l_bookid.Font = new System.Drawing.Font ( "Arial", 12f); l_bookid.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; l_booktitle.Location = new System.drawing.point (24, 108); l_booktitle.text = "Title:"; l_booktitle.size = new system.drawing.size (142, 20); l_booktitle.font = new system.drawing.font ("Song body ", 12f); l_booktitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; l_bookauthor.Location = new System.Drawing.Point (24, 160); l_bookauthor.Text =" Analysis: "; l_bookauthor.Size = new System.Drawing .Size (142, 20); l_bookauthor.font = new system.drawing.font ("Song", 12F); l_bookauthor.textalig n = System.Drawing.ContentAlignment.MiddleCenter; l_bookprice.Location = new System.Drawing.Point (24, 212); l_bookprice.Text = "price:"; l_bookprice.Size = new System.Drawing.Size (142, 20) ; l_bookprice.Font = new System.Drawing.Font ( "Arial", 12f); l_bookprice.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; l_bookstock.Location = new System.Drawing.Point (24, 264); l_bookstock.Text = "Books Number:"; l_bookstock.size = new system.drawing.size (142, 20); l_bookstock.font = new system.drawing.font ("Song"

, 12F); l_bookstock.textalign = system.drawing.contentalignment.middleCenter; // The following settings The properties of the function buttons used in the program and the corresponding event delete.location = New System.drawing.Point (104, 352); Delete.forecolor = system.drawing.color.black; delete.size = new system.drawing.size (80, 24); delete.font = new system.drawing.font ("Song", 9F); delete.text = "Delete Record"; Delete.Click = New System.EventHandler (Godelete); Update.Location = New System.drawing.Point (204, 352); Update.ForeColor = System.drawing.color.black; Update.Size = New system.drawing.size (80, 24); update.font = new system.drawing.font ("Song", 9F); Update.Text = "Modify Record"; Update.Click = New System.EventHandler (goupdate ); firstystem.location = new system.drawing.point (64, 312); firstRec.ForeColor = system.drawing.color.black; firstRec.size = new system.drawing.size (40, 24); firstRec.font = New System.drawing.Font ("Song", 9F); firstRec.Text = "First Record"; FirstRec.click = New System.EventHandler (Gofirst); PreviousRec.Location = New Syste; PREVIOSTE M. Drawing.Point (136, 312); PreviousRec.ForeColor = system.drawing.color.black; previousRec.size = new system.drawing.size (40, 24); PreviousRec.Font = new system.drawing.font ( "Arial", 9f); previousrec.Text = "Previous"; previousrec.Click = new System.EventHandler (GoPrevious); nextrec.Location = new System.Drawing.Point (208, 312); nextrec.ForeColor = System .Drawing.color.black; nextrec.size = new system.drawing.size (40, 24); NextRec.Font = new system.drawing.font ("Song", 9F); NextRec.Text = "Next";

nextrec.Click = new System.EventHandler (GoNext); lastrec.Location = new System.Drawing.Point (280, 312); lastrec.ForeColor = System.Drawing.Color.Black; lastrec.Size = new System.Drawing. Size (40, 24); LastRec.Font = New System.drawing.Font ("Song", 9F); LastRec.Text = "Tail Record"; LastRec.Click = New System.EventHandler (Golast); label1.location = New System.drawing.Point (60, 20); Label1.Text = "Use Visual C # to modify and delete records in the database"; label1.size = new system.drawing.size (296, 24); label1.forecolor = System.drawing.systemcolors.desktop; label1.font = new system.drawing.font ("Song", 14F); // Setting the Properties of the main form of the program this.text = "Use Visual C # to modify and delete Record in the database! "; This.autoscalebasesize = new system.drawing.size (5, 13); this.formolderstyle = formborderstyle.fixedsingLe; this.clientsize = new system.drawing.size (394, 425); // The main form is added to the component this.controls.add (delete); this.controls.add (update); this.controls.add (lastrec); this.controls.add (next.controls.add (PreviousRec) THIS.CONT rols.Add (firstrec); this.Controls.Add (t_bookstock); this.Controls.Add (t_bookprice); this.Controls.Add (t_bookauthor); this.Controls.Add (t_booktitle); this.Controls.Add (t_bookid ); this.Controls.Add (l_bookstock); this.Controls.Add (l_bookprice); this.Controls.Add (l_bookauthor); this.Controls.Add (l_booktitle); this.Controls.Add (l_bookid); this.Controls .Add (label1);} // "Delete Record" Corresponding Event Protected Void Godelete (Object Sender, System.EventArgs E) {Try {// Connect to a database strcon = "provike = microsoft.jet.Oledb.4.0 Data Source = Sample.mdb "; OLEDBCONNECTION MyConn =

new OleDbConnection (strCon); myConn.Open (); string strDele = "DELETE FROM books WHERE bookid =" t_bookid.Text; OleDbCommand myCommand = new OleDbCommand (strDele, myConn); // delete the specified records from the database myCommand.ExecuteNonQuery (); // Remove the specified record in DataSet MyDataSet.Tables ["Books"]. Rows [mybind.position]. Delete (); mydataset.tables ["books"]. AcceptChanges (); myconn.close (); MyConn.close (); } catCH (Exception ED) {messageBox.show ("Delete Record Error Message:" Ed.toTString (), "Error!");}} // The "Modify Record" button corresponds to the event Protected Void GOUPDATE (Object Sender, System.Eventargs e) {INT i = mybind.position; try {// Connect to a database strCon = "provider = microsoft.jet.Oledb.4.0; data source = sample.mdb"; OLEDBConnection myconn = new OLEDBCONNECTION (STRCON ); MyConn.open (); // Modify the specified record from the database string strupdt = "Update books set booktitle = '" t_booktitle.text ", BookAuthor ='" t_bookauthor.text ", bookprice =" T_BookPrice.Text ", BookStock =" T_bookstock.text "Where bookid =" t_bookid.text; oleDbcommand mycomma Nd = new OLEDBCOMMAND (STRUPDT, MyConn); MyCommand.ExecuteNonQuery (); myconn.close ();} catch (exception ed) {messagebox.show ("Modify specified record error:" Ed.toToString (), "Error! ");} mybind.position = i;} //" Tail Record "button corresponds to the event protected void golast (Object sender, system.eventargs e) {mybind.position = mybind.count - 1;} //" Next "Button Corresponding Event Protected Void Gonext (Object Sender, System.EventArgs E) {IF (mybind.position == mybind.count - 1) MessageBox.show ("

Already tail record! "); elseMybind.position = 1;} //" Previous "button Corresponding event protected void goprevious (object sender, system.eventargs e) {if (mybind.position == 0) MessageBox.show (" has arrived First record! "); Elsemybind.position - = 1;} //" First Record "button The event protected void gofirst (Object sender, system.eventargs e) {mybind.position = 0;}} 4. Compile the source program Code, generate execution files:

After getting the data.cs source code, you can get the execution file Data.exe after compiling the command to compile the command.

CSC / T: Winexe /R :system.windows.Forms.dll /R :system.data.dll data.cs

5. Summary:

This article mainly introduces how to use Visual C # to delete and modify the record. And some important issues and processes that should be paid attention to when dealing with these operations. If your machine has met the runtime required by this article, create a sample.mdb database in the generated execution file directory, create a Books data table in the database, and the structure of the data table can be established in accordance with the structure provided above. Once you have all, you can run the program and enjoy the pleasure of the data operations brought by Visual C #.

转载请注明原文地址:https://www.9cbs.com/read-71120.html

New Post(0)