Example of C # and database Access Technology Summary (ix)

Source: Internet
Author: User

  

Instance

Update record

In this example, create a text box for the user to enter the student number and name, and several update information buttons that correspond to the different action types, and then perform the appropriate action when the user enters the information and clicks the corresponding button. Knowledge about server information validation is also exposed in this instance.

(1) Create a new Windows application application named Updatetest, add 2 Label controls to the default Forml.cs, 2 TextBox controls, 3 button controls, and set the properties of these 4.7 controls as shown in Table 7.

Table 4.7 Control Properties

Control type ID Property Text property

Label Lbluserid Number:

Label Lblusername Name:

text Box Txtuserld

text Box txtUserName

Button BtnExecute1 Stitching string

button BtnExecute2 Using Parameters

button btnExecute3 using Stored procedures

(2) Adjust the position of the control (as per your preference)

(3) Double-click the "Stitch string" button, Register button Btnexecute button, clicking Event Btnexecute1_click,

Then switch to the Design view of the Form1.cs page, double-click the use parameters and then the use stored Procedure button to register the corresponding button click events Btnexecute2_click and Btnexecute3_click.

(4) in the Form1.cs file, first introduce the namespace System.Data.SqlClient, and then add a method named Checkinfo, the return value is type bool, the code is as follows:

 

BOOLCheckinfo () {//Determine if the study number is entered    if( This. TxtUserID.Text.Trim () = ="") {Alert ("The school number is incomplete."); return false; }Else if( This. TxtUserName.Text.Trim () = ="")//determine if the name is entered{Alert ("The name is not complete"); return false; }//information check through    return true;}

// The alert is another method of customizing that pops up a dialog box, defined as follows:        void Alert (string  message)        {            MessageBox.Show (null" informational hint "  , MessageBoxButtons.OK, messageboxicon.information);        }
        //write the following code in Btnexecute1_click:        Private voidBtnexecute1_click (Objectsender, EventArgs e) {            //information Check            if( This. Checkinfo ()) {//Take value                stringUserid= This. TxtUserID.Text.Trim (); stringUsername= This. TxtUserName.Text.Trim (); //New Connection ObjectSqlConnection conn=NewSqlConnection (); Conn. ConnectionString="Data source= (local); Initial catalog=student;integrated Security=sspi"; //Stitching Command String                stringupdatequery="Update studentinfo set sname= '"+username+"'"+"where id= '"+userid+"'"; //new Command ObjectSqlCommand cmd=NewSqlCommand (Updatequery,conn); Conn.                 Open (); //Save Execution Results                intRecordsaffected=cmd.                ExecuteNonQuery (); Conn.                Close (); //Prompt ResultsAlert ("the number of updated data is"+RecordsAffected); }        }
        //write the following code in Btnexecute2_click:        Private voidBtnexecute2_click (Objectsender, EventArgs e) {            //information Check            if( This. Checkinfo ()) {//Take value                stringUserid= This. TxtUserID.Text.Trim (); stringUsername= This. TxtUserName.Text.Trim (); //New Connection ObjectSqlConnection conn=NewSqlConnection (); Conn. ConnectionString="Data source= (local); Initial catalog=student;integrated Security=sspi"; //Stitching Command String                stringupdatequery="update studentinfo Set [email protected] where [email protected]"; //new Command ObjectSqlCommand cmd=NewSqlCommand (Updatequery,conn); //Adding ParametersCmd. Parameters.Add (NewSqlParameter ("@userName", UserName)); Cmd. Parameters.Add (NewSqlParameter ("@userId", userId)); Conn.                Open (); //Save Execution Results                intRecordsAffected =cmd.                ExecuteNonQuery (); Conn.                Close (); /*try {Conn.                    Open (); Save execution Result int RecordsAffected = cmd.                ExecuteNonQuery (); } catch (Exception err) {MessageBox.Show (err.                Message, "Failed to modify the record"); } finally {if (conn. state = = ConnectionState.Open) {Conn.                    Close (); }                }*/                //Prompt ResultsAlert ("the number of updated data is"+RecordsAffected); }        }
        //write the following code in Btnexecute3_click:        Private voidBtnexecute3_click (Objectsender, EventArgs e) {            //information Check            if( This. Checkinfo ()) {//Take value                stringUserId = This. TxtUserID.Text.Trim (); stringUserName = This. TxtUserName.Text.Trim (); //New Connection ObjectSqlConnection conn =NewSqlConnection (); Conn. ConnectionString="Data source= (local); Initial catalog=student;integrated Security=sspi"; //new Command ObjectSqlCommand cmd =NewSqlCommand ("Updatestudentinfo", conn); //specify command type as stored procedureCmd.commandtype =CommandType.StoredProcedure; //Adding ParametersCmd. Parameters.Add (NewSqlParameter ("@userName", UserName)); Cmd. Parameters.Add (NewSqlParameter ("@userId", userId)); Conn.                Open (); //Save Execution Results                intRecordsAffected =cmd.                ExecuteNonQuery (); Conn.                Close (); //Prompt ResultsAlert ("the number of updated data is"+RecordsAffected); }        }

(9) After entering the information in the school number and name, click any button to test the update results.
For example:

Click any button after you enter the enrollment number "2007102001" and the name "XXX" respectively.


Code explanation
After the introduction of the System.Data.SqlClient namespace, SQL Server was used. NET data provider to update the data.
The data is checked using the Checkinfo method before the data is updated to see if the user entered valid information in the name and number two text boxes, if both of the input information is valid, the method returns True, otherwise false is returned.

The method is implemented as follows:

            //Determine if the study number is entered            if( This. TxtUserID.Text.Trim () = ="") {Alert ("The school number is incomplete."); return false; }            Else if( This. TxtUserName.Text.Trim () = ="")//determine if the name is entered{Alert ("The name is not complete"); return false; }            //information check through            return true;

  When the user enters incorrect information, Checklnfo calls the alert method to display the prompt message dialog box.

The alert method is actually some of the parameters of the fixed MessageBox.Show method, using it to pop up the dialog, the alert method implementation is very simple, just need the following sentence code:  

MessageBox.Show (null, message," informational hint ", messageboxbuttons.ok,messageboxicon.information);

Where the message is a parameter accepted by the alert method.

In 3 button click events, the program code to implement the corresponding data update operations, these operations are explained in detail before, here is no longer mentioned.

Example of C # and database Access Technology Summary (ix)

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.