laitimes

C# Programming. VR basic tutorial

author:Teacher Zhang Chenguang

C# programming

Chapter 1: C# Basics Video: https://edu.csdn.net/course/detail/27107

One. Knowledge points

1.C# Concepts and Understanding

2. Syntax format

3. Case practice

Two. focus

2.1 Syntax Format

Three. content

3.1 C#: C sharp. C-->C++-->C++, Java is from the C series, born on the basis of C++.

Ms Microsoft developed, and now C# also implements cross-platform, a bit late.

When C# was first developed, it was only suitable for Microsoft's platform (Windows Series, XP, 2000, 7 10, etc.), and the program was designed, not just the Windows Series

There are also Linux, Mac, Unix, Android, and other operating systems.

Application scenarios: the most are C/S series programs (software), C: client clients; S: Server; servers; Internet café systems, screen advertisements (red spiders), ticket sales, stock speculation, hacker cracking and so on. Asp.Net: Web-side development programs, web programs, but cross-platform is not good, the main thing is that Microsoft is not an Internet company, selling operating systems. Now Unity3D software, do VR/AR online games, the core language is C#.

3.2 Syntax format:

The use of variable names: JS, variable names are case-sensitive; initials: can it be a number??? _ +

C#: It is a strongly typed language, that is, as long as there is an error, it will be reported in VS2012;

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;//Namespace: Zone classification; namespace chapter01{ //class is the class Program

{

How to run: "Debug" has a "Start Debugging", shortcut key: F5; but will flash;

Don't want to flash by: Ctrl+F5; "Debug" --" "Start execution (no debugging)"

3.3 Placeholders;

Previously all were concatenated variables and strings using + ;

{0}, {1}--> variable 1, variable 2

static:static;void:no type returned;Main:門;string[]args:argument; There is also a door inside the program; it cannot be moved, that is, the entrance to the program; The argument is the janitor, you need to register; static void Main(string[] args) { //primitive data type; int age = 18; float height = 1.8F; After the float type, you need to add F; double weight = 120; The default C# decimal is of type double; char flag = 'Y'; Character type, enclose the data in single quotation marks with ''; bool biaozhi = true;//bool: true or false //string type; String name = "zhangsan"; Strings are double quotes; Output; Write(): no line breaks; WriteLine(): line breaks; Console.Write(name); Console.Write(age); } }}

The area of the circle; S=PI*r*r //1. Define variables and assign values; Console.Write ("Please enter the radius of the circle:"); double r;//3 is a fixed value; you can enter it yourself; r = double. Parse(Console.ReadLine()); const double PI=3.1415926; Constants are defined using const; constant names: uppercase; double s = PI * r * r; PI = 2; Constants cannot be assigned more than once; Console.WriteLine (the area of r + "is:" + s); Do not use Ctrl+F5; Finally accept; Console.ReadLine();

3.4 Control structure:

3.41 Sequential Structure

3.4.2 Branch structure: if statement switch statement;

Cyclic structure:

Four. homework

4.1 Homework

Chapter 2: Loops and Strings

Placeholder; Two numbers add and subtract multiply and divide int num1, num2; Console.WriteLine ("Please enter the number 1:"); num1 = int. Parse(Console.ReadLine()); // Converts a string to an int type; Console.WriteLine ("Please enter the number 2:"); num2 = int. Parse(Console.ReadLine()); // Converts a string to an int type; 2. Output; Rule: {0}, corresponding to "", followed by the first variable; {1}: the second variable; Console.WriteLine("{0}+{1}={2}",num1,num2,(num1+num2)); Console.WriteLine("{0}-{1}={2}", num1, num2, (num1 - num2)); Console.WriteLine("{0}*{1}={2}", num1, num2, (num1 * num2)); Console.WriteLine("{0}/{1}={2}", num1, num2, (num1 / num2)); Console.WriteLine("{0}%{1}={2}", num1, num2, (num1 % num2)); Console.ReadLine();

branch statements, swtich statements; According to the time, the output is (789) pm (141617) evening (202122); int num; Console.Write ("Please enter a time:"); num = int. Parse(Console.ReadLine()); 2. Business judgment; switch(num){ case 7: case 8: case 9: Console.WriteLine ("{0} am", num); break; case 14: case 16: case 17: Console.WriteLine ("{0} afternoon", num); break; case 20: case 21: case 22: Console.WriteLine ("{0} night", num); break; default: Console.Write ("Problematic"); break; C#: Strongly typed, must have a break; } Console.ReadLine();

1.循环(do while/while/for/foreach)

2. Strings String and StringBuilder

3. Type conversion

1. At least 2 cycle masters;

2. Use of strings;

1. Loops (cycles with fixed numbers, cycles with irregular numbers)

Steps of the loop:

1.1 Initialize the variable i

1.2 Conditions for looping (when to go looping, meaning there is an end condition)

1.3 Loop code work, things to do;

1.4 Counter

}

What is the difference between do while and while loops?

do while: execute at least once; because the do while loop executes the code first, and then judges;

static void Main(string[] args) { // less conditional judgment, reduced number of loops; for (int i = 1; i <= 100; i+=2 ) { Console.Write(i+" "); } Console.Read();

foreach format:

2. Number of daffodils:

Three digits between 100-999; the first step is to find the range;

153=1^3+5^3+3^3

The second step is to determine: one digit ten hundred digits

% /

gw = 153 % 10; Single bit %10 to find the remainder; sw = 153 / 10 % 10;// Ten in two steps; bw = 153 / 100;//hundred/10 divisible by Console.Write("{0}", gw); Console.Write("{0}",sw); Console.Write("{0}",bw);

for(int i=100;i<=999;i++){

int i = 0; do{ if (i % 2 == 0) Console.Write(i + " "); i++; }while(i<0); Console.Read();

Less conditional judgment, reduced number of cycles; for (int i = 1; i <= 100; i+=2 ) { Console.Write(i+" "); } Console.Read();

C#: Array format [], the subscript of the array starts from 0 to the length of the array -1; int[] arr = { 1,3,5,7,9}; Output the elements in the array; Array name [subscript] Console.WriteLine(arr[0]); Console.WriteLine(arr[1]); Console.WriteLine(arr[2]); Console.WriteLine(arr[3]); Console.WriteLine(arr[4]); Error: the index of the array is out of bounds; Console.WriteLine(arr[5]); Output the elements in the array; i:0 1 2 3 4 //for (int i = 0; i <= 4; i++ ) //{ // Console.Write(arr[i]+" "); } foreach(int n in arr){ //n:arr; n means to take the elements from the array one by one; Console.Write(n +"\t"); } Console.Read();

The third part determines the equation conditions for daffodils and then outputs the results;

3. String class;

int gw, sw, bw; Represents 100 digits //i: 153; for (int i = 100; i <= 999; i++) { gw = i % 10; Single bit %10 to find the remainder; sw = i / 10 % 10;// Ten in two steps; bw = i / 100;//hundred/10 divisible if(i==gw*gw*gw+sw*sw+bw*bw*bw){ Console.WriteLine(i); } } Console.Read();

The string position is also starting from 0; String str = "Today is a good day, I was criticized by this teacher, Wei Zibo, is a good classmate"; Console.WriteLine(str. Contains ("Wei Zibo")); // Does it contain Console.WriteLine(str. EndsWith ("Zibo")); // ends with a substring console.WriteLine(str. StartsWith ("today"); // starts with a substring; Console.WriteLine(str. IndexOf ("individual"); //3 the location where it first appeared; Console.WriteLine(str. Insert (3, "Sunny Day Really Is")); Console.WriteLine(str. LastIndexOf ("units"); Console.WriteLine(str. Remove(3)); Console.WriteLine(str. Replace ("Wei Zibo", "Wei Big Handsome Brother")); Console.WriteLine("Abcd". ToUpper()); Console.WriteLine("Abcd". ToLower()); Console.WriteLine(str. Substring(3,5)); //3: Starting position; 5 the length of the interception; Formatted strings: {0}, {1}, {2} //Format (string plus placeholder, value 1, value 2,.., value n) String name="Zhao Junjie"; int age=88; String str2 = String.Format ("Our squad leader is {0}, age: {1}", name, age); The whole format string can be used by the console and the game; winform can also be used; // the value is more convenient; Console.WriteLine(str2); Console.Read();

1. Implicit conversion (automatic conversion) //int age = 20; double age2 = age; double:floating-point type: decimal type, the range is relatively large; //Console.WriteLine(age); Console.WriteLine(age2); 2. Explicit conversion; double height = 2.87; int height2 =(int)height; Because the double type range is relatively large;

Precede the large type (small type)

Homework 1 2 3

Chapter 3 Double Loops and Arrays

1. Double loop

2. Arrays

1. Interview questions

1. Double loop: Nesting of loops

The loop generally has up to 3 layers, requiring everyone to be proficient in double loop interview questions; master the solution ideas of interview questions.

right-angled triangle:

Console.WriteLine(height); Console.WriteLine(height2); The problem that arises is that the data is lost; int height3 = Convert.ToInt32(height); Switching from double type to integer type is rounded; Console.WriteLine("-->"+height3); 3. Type conversion; String --》integer string s = "222"; int num2 = int. Parse(s);//parse (string argument) Console.WriteLine(num2); int num3 = Convert.ToInt32(s); Console.WriteLine(num3); Console.Read();

/// <summary> /// * /// * * * /// * * * * * /// * * * * * * * /// * * * * * * * * *

/// </summary>

Odd triangles:

isosceles triangle:

class Program { static void Main(string[] args) { for (int i = 1; i <= 5;i++ ) { //i:行数;1 2 3 4 5;2i:2 4 6 8 10 for (int j = 1;j<=2*i-1 ;j++ )//j:*的个数;1 3 5 7 9 { Console.Write("* "); } Console.WriteLine(); } Console.Read(); } }

<summary> /// * /// * *//* *//* *//* * /// * **/ * **/ </summary> class Program { static void Main(string[] args) { // All such interview questions: Outer loop control line; i stands for the number of rows for (int i = 1; i <= 5; i++) { //Console.WriteLine ("number of output lines"+i); How to do a *in line 1; a **in line 2;; Line 3: ***; for (int j = 1; j<=i; j++) //j: represents the number of * of the output; { Console.Write("* "); } Console.WriteLine(); //After a line is completed: wrap } Console.Read(); } }

/// <summary> /// * /// * * * /// * * * * * /// * * * * * * *

///* * * * * * * * *

Letter triangle

Arrays: concepts: a collection of the same data type;

Why use ???

The average grade of 42 people in our class is required??? > 42 variables

Syntax format:

Data type [] Array name=new data type length]

int[]ages=new int[3]; The length of the array is 3;

int[]score=new int[42];

String[]names=new String[42];

Assignment of arrays: The values must be consistent with the array data type;

Array name [subscript]=value Subscript starts at 0; to the length of the array -1

score[0]=88;

score[1]=90;

ages={}; It is also possible to use {} to assign a value;

/// /// </summary> class Program { static void Main(string[] args) { for (int i = 1; i <= 5;i++ ) { for (int j = 5 - i; j >= 1;j-- ) { Console.Write(" "); } for (int j = 1; j <= i;j++ ) { Console.Write("* "); } for (int j = 1;j<i ;j++ ) { Console.Write("* "); } Console.WriteLine(); } Console.Read(); } }

1.page 50

2.page 53 Hands-on Exercise 1

3. Capable students prepare for "bubbling sorting" on their own

4. Record screens, be a teacher yourself, have notes, have a voice, explain page77 homework 3.

Chapter 4: Review Lessons

1. Find the average of the 5 array elements

1. Define the array length; String[] names = new String[5]; int[] salary = new int[5]; String[]names=new String[5]{"Li Ying","popsicles","ice cream","chicken legs","hamburgers"}; names[0]="Lee Nature"; names[2]="Ma Dongmei"; names[3] = "Simon Bragging"; names[4] = "Dongpo"; names[1] = "Qu Elder"; names[5] = "monk"; The maximum length is 5-1=4//2 input; Length: The length of the array; for (int i = 0; i < names. Length; i++) { // Console.Write ("Please enter the name of the {0} classmate:",i+1); names[i] = Console.ReadLine(); Console.Write ("Please enter the salary of the {0} classmate:", i+1); salary[i] = Convert.ToInt32(Console.ReadLine());//or: int.parse() //} //3. Output for (int i = 0; i < 5; i++) { Console.WriteLine ("salary for {0} classmates: {1}",names[i],salary[i]); } Console.Read();

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ararydemo{ /// <summary> /// Target: average of an integer array of length 5;

2. Find the factorial and factorial sum of the number n

class Program { static void Main(string[] args) { //1.declare arrays; Use [] to define; 5 int[] arr = new int[5]; 2. Input; The easiest way to assign; Use loops to assign values; Find the law: arr[] array name[] Polaris[0]-Polaris[9] //Royal One [0]--Royal One[4]; Hotel name [house number] // Array name [subscript] -> the law of subscript: 0 --4; Increment; arr[0] = 1; arr[1] = 2; arr[2] = 10; arr[3] = 20; arr[4] = 78; for (int i = 0; i <= 4; i++) { Console.Write ("Please enter {0} element", (i+1)); // placeholder, the value matches //Console.Write ("Please enter first" + (i + 1) + "elements"); Acceptance; arr[i] = int. Parse(Console.ReadLine()); Type conversion; int.parse(); Convert.ToInt32() } //3. Output; It is better to write another loop; Console.WriteLine(arr[0]); int sum=0; sum and //for (int i = 0; i < arr. Length; i++) //{ // Console.WriteLine(arr[i]); sum = sum + arr[i]; } // can also be used in the following format foreach (int num in arr) { Console.WriteLine(num); sum = sum + num; } //int avg = (arr[0] + arr[1] + arr[2] + arr[3] + arr[4])/5; int avg = sum / 5; Console.WriteLine ("Average: {0}", avg); Console.Read(); } }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;

3. Find the position of the substring in the mother string and its number

4. Assignment:

namespace Factorial{ /// <summary> /// Factorial: n!=n*(n-1)!; 4!=4*3*2*1; </summary> class Program { static void Main(string[] args) { Console.Write("Please enter the order multiplied by a number:"); Hint message int n = int. Parse(Console.ReadLine()); //n: Number for factorial; Hypothesis: 4//Find 1*2*3*4//Find 1!+2!+3!+4! int ji = 1;//Set a variable with an initial value of 1; int sum = 0; for (int i = 1; i <= n; i++ ) { ji = ji * i;//ji=1*1; ji=1*2=2; ji=2*3; sum += ji; sum=sum+ji; } Console.WriteLine ("The factorial of {0} is: {1}", n, ji); Console.WriteLine ("factorial sum {0}", sum); Console.ReadLine(); } }}

String s1 = "Heavy snow is coming, heavy snow mega year, my name is heavy snow"; String keyword = "heavy snow"; This is considered two; //Console.WriteLine(s1. IndexOf(keyword)); Get the location of keyword keywords; Console.WriteLine(s1. LastIndexOf(keyword)); int index=0; Female string. IndexOf (substring, the starting position of the lookup), when the starting position changes, continue to find the position of the substring in the original parent string from the new position; Console.WriteLine(s1. IndexOf(keyword,1)); Console.WriteLine(s1. IndexOf(keyword, 6)); while ((index = s1. IndexOf(keyword, index)) != -1) {// condition is not equal to -1, then loop; Inside the loop is the data string console.WriteLine ("substring position: {0}", index); Next, shouldn't you let index go backwards; index = index + keyword. Length; 0+2; } Console.Read();

4.1 The first question of the screen recording, you need to add annotations, and explain yourself, avatar, sound;

4.2 Preview Chapter 5

Chapter 5 Form Controls

1. Form

2. Common controls

3. Command statements

1. Master forms and common controls

2. Learn the properties and events of commonly used controls

1. The concept of forms

windows: windows; visualization windows;

New Windows Form--"Name: frmWin

Right-click -- > properties; set the form's text:title; name:default to the frmWin you just wrote

BackColor: Background color

Set it up: programs-->

Main() below:

Application.Run(new frmWin());

StartPosition: Startup location; CenterScreen;

MaximizeBox: whether the maximize button can be used; true: can be used; false: grayed out; After this is set, it is not necessarily unchanged size;

FormBorderStyle: None: no border; FixedSingle: single border;

Form form: Web page: Form, you can put form elements, survey pages, etc.; in fact, the form is a container, you can put other controls. Equivalent to a restaurant table; containers such as GroupBox are equivalent to plates;

steps:

1. Look for the controls

2. Set the properties

3. Write code

2. Login form effect

1. Label: Label; function, just prompt information;

2.TextBox text box: used to enter information;

3. Button button; used for clicking; interactive use;

Account text box: txtName;

Password box: txtPwd

Login button: btnLogin

Reference Code:

private void btnCancel_Click(object sender, EventArgs e) { this. Close();//Close } private void btnLogin_Click(object sender, EventArgs e) { //MessageBox.Show(txtName.Text);//bullet box; MessageBox.Show(txtPwd.Text); String name = txtName.Text; Define two variables that accept the values of the Username text box and the Password box; String pwd = txtPwd.Text; if (txtName.Text.Equals("83193980") && txtPwd.Text.Equals("88889999")) if (name. Equals("83193980") && pwd. Equals("88889999") { MessageBox.Show } else { MessageBox.Show ("Login failed"); } }

3.items

selectedIndex Items Item

4.1 Login Form Perfect

Chapter 6 Controls

1. Picture frame

2. Multi-form call

3. Control continues

4. Message box

1. Call between multiple forms

1. Picture frame case:

Declare variables under the form

Previous button code:

Next button code:

Declare a numeric variable; i default value is 0; we set it to 1 private int i=1;

{ // has such a property; Image Path: ImageLocation //MessageBox.Show (pictureBox1.Image); i--; if (i == 0) i = 5; pictureBox1.ImageLocation = String.Format("img/bg{0}.jpg",i);

Exit button code (two tests)

3. MessageBox(): Message box

4. Menu bar

Add icon:

Is the Form form: ICON property, find the teacher to give the ico icon;

RichTextBox directly sets the parking;

TextBox: Need to set to multi-line first, and then set Dock to Fill (you can pull it out to test)

To set the right-click menu, you need to first find the text box and set its properties to ContextMenuStrip

Rename the text box (or rich text box) to txtNotepad

Text box: text_changed()

Rich text box: SelectionChanged

img/bg numeric variable .jpg; The numeric variable is i //pictureBox1.ImageLocation = "img/bg"+i+".jpg"; i++; if (i == 6) i = 1; pictureBox1.ImageLocation = String.Format("img/bg{0}.jpg",i);

The second form is not closed. this. Close(); Application.Exit(); The app exits

Can also be used when deleting; MessageBox: Message box; +20: Multi-meaning method; type DialogResult result=MessageBox.Show ("Do you shut down the Royal One Hotel System?", "Prompt Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { //event to close; cancel attribute is false; It's off. e.Cancel = false; } else { e.Cancel = true; }

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Windows.Forms; namespace demo61{ public partial class Form1 : Form { private int i = 9; public Form1() { InitializeComponent(); } /// &lt;summary&gt; /// Give a hint when the form is closed; /// e: Event parameter object; </summary> /// &lt;param name="sender"&gt;</param> /// &lt;param name="e"&gt;</param> private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Can also be used when deleting; MessageBox: Message box; +20: Ambiguous method; typing //DialogResult result=MessageBox.Show ("Do you shut down the Royal One Hotel system?", "Prompt Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) //{ // // event to close; cancels the property as false; It's off. e.Cancel = false; } //else { // e.Cancel = true; } private void file ToolStripMenuItem_Click(object sender, EventArgs e) { } private void exit XToolStripMenuItem_Click(object sender, EventArgs e) { this. Close(); } private void revokes UToolStripMenuItem_Click(object sender, EventArgs e) { this.txtNotepad.Undo(); Revocation; Called is the system's method } private void cut ToolStripMenuItem_Click (object sender, EventArgs e) { txtNotepad.Cut(); Shearing method;

private void copy ToolStripMenuItem_Click(object sender, EventArgs e) { txtNotepad.Copy(); } private void paste ToolStripMenuItem_Click(object sender, EventArgs e) { txtNotepad.Paste(); //? } private void to get bigger ToolStripMenuItem_Click (object sender, EventArgs e) { // set the font, you need to give Font a specific font object; I have set the variable i++ txtNotepad for you.Font = new Font ("bold", i++); } private void smaller ToolStripMenuItem_Click (object sender, EventArgs e) { txtNotepad.Font = new Font("bold", i--); } private void bold ToolStripMenuItem_Click (object sender, EventArgs e) { //FontStyle: font style; txtNotepad.Font = new Font ("boldface" txtNotepad.Font.Style | FontStyle.Bold); FontStyle.Italic; //FontStyle.Strikeout; Strikethrough //FontStyle.Underline;//Slideline // Unchanged if currently bold; MessageBox.Show(txtNotepad.Font.ToString()); The first parameter is the previous Font style; Omit the page150 line code; txtNotepad.Font = new Font(txtNotepad.Font, FontStyle.Bold); } private void status bar ToolStripMenuItem_Click(object sender, EventArgs e) { status bar ToolStripMenuItem.Checked = true; Out of the tick; this.statusStrip1.Visible = true; } private void richTextBox1_SelectionChanged(object sender, EventArgs e) { if (txtNotepad.SelectedText.Length != 0) { CopyToolStripMenuItem.Enabled = true; Cut ToolStripMenuItem.Enabled = true; } } /// &lt;summary&gt; /// This one text box changes event

Chapter 7 Control Two

1. Master the purpose of the control

2. Master the main properties of the control

3. Master the skills of using the control

1. Clock control

2. Toolbar, ImageList

1. The Tool strip control is composed of system. The Windows.forms.Toolstrip class provides a role to create easy-to-customize standard toolbars that support advanced user interface and layout features such as docked, floating, buttons with text and images, drop-down buttons, and so on.

Common properties:

/// &lt;param name="sender"&gt;&lt;/param&gt; /// &lt;param name="e"&gt;&lt;/param&gt; private void txtNotepad_TextChanged(object sender, EventArgs e) { } //颜色:ForeColor 前景色;BackColor:背景色; private void 红色ToolStripMenuItem_Click(object sender, EventArgs e) { txtNotepad.ForeColor=Color.Pink; } }}

Display by property

DisplayStyle image and text display mode, generally ImageAndText

The Image button or the picture on the label

ImageScaling image size

The text displayed on the Text tag

TextImageRelation Image and Text Relative Position, General ImageAboveText

Property Description

Whether Multiline can display tabs on one line

TabPages sets the collection of tab pages on the control

The index of the SelectedIndex tab page

SelectedTab The currently selected tab page

2. TabControl (tab)

3. Timer control

What is it?

What is it for?

control. It is invisible.

Used in background processes. By raising the Timer event, the Timer control can regularly execute code at intervals. That is, you can set the time for the Timer control according to your own needs, and timer executes the code every once in a while (this code can be written according to the functions you need. )

The frequency with which the Interval event occurs, in milliseconds

Enabled Gets or sets whether the timer is running

Event Description

Tick events that occur at intervals specified

Method Description

Start starts the timer

Stop Stop timer

Property value

Name tmDate

Interval 1000 (1 second = 1000 ms)

4.ImageList

Case: Dynamic album

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace demo61{ public partial class frmImage : Form { //To make 0 1 2 3 4 5, you need to define variables; int i = 0; public frmImage() { InitializeComponent(); } /// &lt;summary&gt; /// Change the picture every tick in clock time /// imageList: List of images; each item in it is an image /// images: many pictures; images[0] - is the first picture;

Marquee lights and color changes

/// &lt;param name="sender"&gt;&lt;/param&gt; /// &lt;param name="e"&gt;&lt;/param&gt; private void timer1_Tick(object sender, EventArgs e) { if (i &gt; 80) i = 0; this.pictureBox1.Image=this.imageList1.Images[i]; i++; } private void button1_Click(object sender, EventArgs e) { this.timer1.Enabled = true; // this.timer1.Start(); } private void button2_Click(object sender, EventArgs e) { this.timer1.Stop(); } //快 private void radioButton1_CheckedChanged(object sender, EventArgs e) { this.timer1.Interval = 100; } //中 private void radioButton2_CheckedChanged(object sender, EventArgs e) { this.timer1.Interval = 500; } //慢 private void radioButton3_CheckedChanged(object sender, EventArgs e) { timer1. Interval = 1000; } }}

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;

namespace demo61{ public partial class frmGun : Form { //color change, defined variable int i=0; public frmGun() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { } /// &lt;summary&gt; /// Marquee, in Html, marquee /// &lt;/summary&gt; /// &lt;param name="sender" &gt;&lt;/param&gt; /// &lt;param=name "e" &gt;&lt;/param&gt; private void frmGun_Load (object sender, EventArgs e) { } //right-to-left; How are colors made up? Three primary colors (red, green, blue) 0-255; 255 strongest light;255 255 255-&gt; white;0 0 0 private void timer1_Tick_1(object sender, EventArgs e) { label1. Left = label1. Left - 2; this. Left += 2; this: is the form; this.label2.Left -= 3; if (label1. Left &lt; -label1. Width) label1. Left = this. Width;//this: Represents the current form width; if (label2. Left &lt; -label2. Width) label2. Left = this. Width;//this: Represents the current form width; Color grading; Color color = new Color();//get a new color; color = Color.FromArgb(255,i,255-i); i += 5; i-value change; if (i &gt; 255) i = 0; label2. ForeColor = color;//foreground view; Change the background color of the form; this. BackColor = color; } }}

Chapter 8 C# and Mysql Database Connections

1. Install plugins and service pack software

2. Download the dll file

3.

1. Access order;

2.

To prepare, note that instead of copying the dll file, nor copying it under bin/debug, add references;

The first step is to familiarize yourself with some common class libraries for C# connection databases

Nongfu Spring: slogan; no production of water, porter;

Data provider: does not produce data, the database produces data; just porters;

Can't be handled in a way that can't be used

Change the target framework as follows:

Order of database access:

1) Establish a database connection

2) Open the database connection

On top of the previous code, add the following code. Conduct tests; conn. Open(); Open(): Indicates that the porter has established contact with the other water plant (database). ConnectionState state = conn. State; MessageBox.Show(state. ToString());//?

3) Write SQL statements

mysql: 4 functions; Additions, deletions, and corrections;

String sql="";

//insert grade(gname) values('S1'),('S2'),('S3')多个 String sql = "insert grade(gname) values('S5')";

String sql = "delete from grade where gname in('S4','S5')"; //id&gt;3

String sql = "update grade set gname='大一' where id=1";

4) Create sql command object SQLCommand

str: is a connection string that connects to a database; String str = "server=localhost; userid=root; password=root; database=school"; Establish a connection; Practice porters; This porter is called conn MySqlConnection conn = new MySqlConnection(str); conn. ConnectionString = str; Assign the porter's connection method (contact, go to Danjiangkou) MessageBox.Show(conn. ConnectionString);

Giving orders to porters; MySqlCommand: Command class, used to execute porter's commands; MySqlCommand comm = new MySqlCommand(sql, conn); The +3 method has three methods of the same name; //comm. Connection = conn; Establish contact with the porter just now; comm. CommandText = sql; Accept orders;

5) Execute SQL commands

int result=comm. ExecuteNonQuery(); Not the query is an addition or deletion if (result &gt; 0) MessageBox.Show else MessageBox.Show ("Insert failed");

6) Close the database connection

Finally there is a closing ??? Why shut it down?

Example 1: Add class information

string constr="server=localhost; userid=root; password=root; database=school"; MySqlConnection conn = new MySqlConnection(constr);//Create database connection object conn. Open();//Open connection object string className = txtClassName.Text; string createDate = txtCreateDate.Text; string sql =string. Format("insert into classes(className,createDate) values('{0}','{1}')",className,createDate); MySqlCommand command = new MySqlCommand(sql, conn);//Create a database command object from sql commands and database connections int count=command. ExecuteNonQuery();//Execute the database's non-query command if (count &gt; 0)// If the return value (number of rows affected) is greater than 0, the entry is successful { MessageBox.Show ("Class Entry Successful"); } conn. Close(); //Close the database connection

1. Proficiency in additions, deletions, and corrections

Chapter 9: Database Connections

1. Dynamically insert data, learn new controls

2. DataReader query information

HasRows returns results if it returns, True if it has a query, false otherwise

FieldCount returns the number of columns in the current row

Method name Description

Close Clears the DataSet of any data

Reader imports XML and data into DataSet

NextResult advances the data reader to the next result

IsDBNull determines whether the data in the column is a NULL value and returns True/False

3. MDI forms

1. Dynamic additions, deletions, and changes

2.DataReader

1. Increase student information

1.1 Create forms, drag and drop controls;

1.2. Change the name;

1.3. Reference database using MySql.Data.MySqlClient;

1.4. Write code;

2. Use of the DataReader control

Properties and methods of the DataReader object

Common methods

The effect is as follows:

Click:

Message add code:

frmAddStu addStu = new frmAddStu();//new New form; addStu.MdiParent = this; The parent form that sets the new form is the current MDI container; addStu.Show();

effect:

Drag the main interface form, and the subform interface runs back and forth with the main form interface.

Four. homework:

4.1 Start the project design database and table; do a good job of analysis;

4.2 Practice lesson content

4.3 To do a hotel you need to study Chapter 8 of ListView by yourself

Chapter 10 DataSets, Data Adapters, and Data Tables

1.DataSet

2. Import data into the data table

2.1 Datasets

2.2 Data Adapters

2.3 Data Tables

3.1 Datasets

1) The role of the data collection: it is to establish a temporary data warehouse in memory, which can be operated and synchronized to the underlying database.

Why use it?

MySqlConnection conn connection object. --" after opening, give comm

MySqlCommand can be added, deleted, and checked. Exam theory (50 questions), these questions are placed in the dataset. After the exam is completed, it is time to submit

, then plug in the network cable, and submit the answers in memory. Equivalent to the temporary database that C# provides to us.

2) Dataset structure:

3) Use DataTable

Collections with rows and columns: Columns and Rows,

Rows is the collection of data for each row in the data table obtained by the query, and the collection can be accessed by index or subscript, for example: through Rows[row number][]]"Class Name"] to obtain this data.

Columns are collections of columns in a table, and the specified column object is obtained through Columns["SOCIAL security numbers"].

3.2 Data Adapters

The data adapter is similar to a charger; the charger finds a phone and goes inside the phone to charge it.

Datatable from data sources to DataSet

When new, see what the parameters are. You can also read books.

The fill() method; the parameter is a dataset object

You can also populate the data table, populating the data table to the common class.

Encapsulated extraction code:

3.3 DataGrid controls

4)DataGridView

DataSource: Data source, you can set a DataTable

SelectionMode: is the selection mode of the table, generally selectFulRowSelect

MultiSelect: Can you select multiple times

ReadOnly: Read-only

After adding the control, conveniently select its several options as shown in the figure, and generally do not add and modify operations in the table.

Queries use the data adapter MySQLDataAdapter, which uses the same usage as MySqlCommand, which can populate an in-memory tabular DataTable object and then have dataSource point to the table.

String str = "server=localhost;userid=root;password=root;database=school;charset=utf8"; MySqlConnection conn = new MySqlConnection(str); conn. Open(); String sql="select id 编号,name 姓名,gender 性别,age 年龄,birth 生日,address 地址 from

student"; Add two arguments: (sql command, connection object) MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn); DataSet temporary database object ds DataSet ds=new DataSet(); Fill (parameter is a dataset object) //adapter. Fill(ds); Index subscript; adapter. Fill(ds, "student"); Another table name // is added to populate the data table. ??? That is, there are several tables in the temporary database of ds??? MessageBox.Show(ds. Tables.ToString()); Without Adding Count is a collection of data tables //MessageBox.Show(ds. Tables.Count.ToString()); is the number of data tables // to populate the data table; A data source is a data table??? dgvStudent.DataSource = ds. Tables[0]; Right is the index subscript, starting from 0; dgvStudent.DataSource = ds. Tables ["Students"]; Table name

3.4 Database Common Code

Suppose there are now 6 tables, each table corresponds to 4 forms, 24, plus an additional 6, 30 forms.

There is a lot of duplicate code:

String conStr = "server=127.0.0.1;userid=root;password=root;database=school;charset=utf8"; MySqlConnection conn = new MySqlConnection(conStr); conn. Open(); String sql = String.Format("select name,pwd from student where name='{0}' and pwd='{1}'",txtName.Text.Trim(),txtPwd.Text.Trim()); MySqlCommand comm = new MySqlCommand(sql, conn); //数据;读者;数据读取器; MySqlDataReader reader=comm. ExecuteReader();

What to do?

3.4.1 A good memory, knock every time, this is called a labor model;

3.4.2 Copy and paste, be faster;

3.4.2 Qualified programmers should be lazy; encapsulate this public code and put it into a class, which is a public class.

The util folder, which contains public class files.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; /*Add mysql namespace; */ using System.Data; Use the System.Data namespace, otherwise; DataTable won't come out; Namespace: chapter08.util

namespace chapter08.util { /// &lt;summary&gt; /// This is a public class that connects to a database /// static: a static keyword; static: immutable; when accessed, the class name can be directly used. Property/Class Name. Method /// &lt;/summary&gt; class DBHelper { static String str = "server=localhost; userid=root; password=root; database=school; charset=utf8"; 1. Get the universal connection object; static, whether it can be removed; public static MySqlConnection getConn() { MySqlConnection conn = new MySqlConnection(str); conn. Open(); Auto-open; return conn; } //2. Close the connection; closes the connection object, so the argument is the connection object public static void close(){ MySqlConnection conn = getConn(); if(conn!=null){ conn. Close(); } } //3. Add, delete, or modify operations; The method has parameters and no ??? public static int update(String sql) { //Common method additions and deletions of the connection object are also generic. MySqlConnection conn = getConn(); MySqlCommand comm = new MySqlCommand(sql,conn); sql is a command statement passed from outside; conn is a generic connection object. int result = comm. ExecuteNonQuery(); return result; } //4. Query operation; The parameter public static DataTable query(String sql) { //The addition, deletion, or modification of the connection object of the universal method is also generic. MySqlConnection conn = getConn(); MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn); Defines a data table object; there is no data; DataTable dt = new DataTable(); At this time, fill in the data table object dt into the adapter. Fill(dt); At this time, dt has data; return dt; } } }

3.5 Click the data table to get the values

Use a variable to accept it; rows: a collection of rows; The first is to get the rows of the data table, // followed by the first few columns of the rows; cells // At this time, the result is a cell object; it is a grid, and our goal is the value therein; //String str = dataGridView1.Rows[0]. Cells[1]. ToString(); MessageBox.Show(str); Get the value *********** //String str2 = dataGridView1.Rows[0]. Cells[1]. Value.ToString(); MessageBox.Show(str2); Get the value of the current row; e: represents the current mouse click event; rowIndex: row number; ColumnIndex: column ordinal; //String str3 = dataGridView1.Rows[e.RowIndex]. Cells[e.ColumnIndex]. Value.ToString(); MessageBox.Show(str3);

3.6 Click Data Table to Pass Values to New Form

Data table code:

The next goal is to display the data on the frmUpdateGrade form; String id = dataGridView1.Rows[e.RowIndex]. Cells[0]. Value.ToString(); String name = dataGridView1.Rows[e.RowIndex]. Cells[1]. Value.ToString(); Declared the form object, and new a bit, new out; frmUpdateGrade updateGrade = new frmUpdateGrade(); updateGrade.id = id; updateGrade.name = name; updateGrade.Show(); When passing values across forms, you should pass id, name to updateGrade;

New form code:

1. Define two properties for the form; id,name public String id;// If it is an int, you need to force the conversion; public String name;

To add code in the form load event:

There is no value at this time; MessageBox.Show (id + "initialize....," + name); When we write frmDataGrid2, two lines of assignment code, the values of id and name are passed. Where are we going to pass this value on??? this: represents the current form object here; txtId.Text = this.id; txtGName.Text = this.name;

To update the button code:

/// &lt;summary&gt; /// 更新按钮代码 /// &lt;/summary&gt; /// &lt;param name="sender"&gt;&lt;/param&gt; /// &lt;param name="e"&gt;&lt;/param&gt; private void btnUpdate_Click(object sender, EventArgs e) { String sql = string. Format("update grade set gname='{0}' where id={1}",txtGName.Text,txtId.Text); int result=DBHelper.update(sql); if (result &gt; 0) MessageBox.Show("更新成功"); else MessageBox.Show("更新失败"); DBHelper.close(); }

4.1 Master three types of content

4.2 Use common database operation classes to add, delete, modify and check;

4.3 All information on the project:

4.3.1 Demand analysis + division of labor (to be handed in before the holiday), which module the specific person does

4.3.2 Design of database tables (on the script, that is, several tables, table names, field names and meanings)

4.3.3 Naming conventions written down (before frm; btn; cmb;)

4.4 DBHelp .cs screen recording explanation

Chapter 1: C# Basics

Read on