优秀的编程知识分享平台

网站首页 > 技术文章 正文

C#WinForm基础编程

nanyue 2025-02-10 13:40:35 技术文章 4 ℃


C#WinForm基础编程 视频课:
https://edu.51cto.com/course/20906.html

第一章:C#基础入门

单词:int,byte,short,long,float,double,char,boolean,string,date,form,console,write,writeLine,read,text,if,else,switch,name,parse

第一节:数据类型和变量

一、数据类型:

基本数据类型

int,byte,short,long

float,double

char

boolean

扩展数据类型

String,Date...所有定义的类型

Form1 f1=new Form1();

二、声明变量:

数据类型 变量名;int a;

数据类型 变量名=变量值; int a=9; String name="张无忌"; "name","Form1"

字符串的值必须用双引号包裹:" ",注意无论什么变量一旦被双引号包裹,都将变成对应的字符串而失去原来的意义。

变量赋值:

int a;a = 8;a = 78;string b = "东方不败";char c = 'n';double num = 56.5;

bool d = true;bool e = false;int f;f = a;Console.WriteLine(a);Console.Read();//仅仅是利用读取方法让程序暂停,能够看到窗口结果。

12345678910111213


int a=9;

int b=a;

是将变量a中的值9复制一份赋值给另一个变量b,变量a中仍然保留原来的值9;

变量命名:

首字母必须是字母、$、下划线_,后面可以跟字母、下划线、数字,不能有特殊字符(&%^#),语言的保留字不能用来命名变量,string ,int,if ,else,true,false,double。。。

第二节:运算符:

一、算术运算符:

/ % + - * ++ --

示例1: 4大碗面,8元一碗;2小碗面,5元一碗;3盘小菜,12每盘;问没人均摊多少?

二、比较运算符

== > < >= <= !=


C# 宿舍管理系统
https://edu.csdn.net/course/detail/27107

第二章:判断 第一节:if条件判断

if,switch

一、单个if-else

if(条件){

代码功能

}else{

另一种代码功能

}

f = a + num * 5;int u = a % 5;int a=9;Console.WriteLine(a++);Console.WriteLine(++a);

12345

int bigCount = 4, litCount = 2, caiCount = 3;double bigPrice = 8, litPrice = 5, caiPrice = 12;double sum = bigCount * bigPrice + litCount * litPrice + caiCount * caiPrice;double avg = sum / (bigCount + litCount);Console.WriteLine(avg);Console.Read();

123456

int a = 7,b=6;bool test = a >= b;Console.Write(test);Console.Read();

1234


示例1:输入一个学生成绩,如果大于等于90分,师傅说给你个武林秘籍,否则,面壁思过


登录界面判断用户名和密码是否正确

退出系统:需要在主窗体的FormClosed事件中添加:Application.Exit();

二、多重if-else

语法:

if(条件1){

语句1;

}else if(条件2){

语句2;

}else{

语句3;

}

判断学生成绩的等级

Console.WriteLine("请输入令狐冲的Java成绩");string sc = Console.ReadLine();//等待用户的窗口输入double score = double.Parse(sc);//将字符串转化为double类型的值if (score >= 90){ Console.WriteLine("奖励《葵花宝典》");}else{ Console.WriteLine("面壁思过");}Console.ReadLine();

1234567891011

if(txt_num2.Text=="0"){ txt_result.Text="除数不能为0";}

123

string username = txt_username.Text;String pass = txt_pass.Text;if (username == "admin" && pass == "1234"){ //MessageBox.Show("用户名密码正确", "成功提示"); FmMain fm=new FmMain();//创建主窗体 fm.Show();//显示主窗体 this.Hide();//让当前登录窗体隐藏}else{ MessageBox.Show("用户名或密码错误","提示");}

12345678910111213

Console.WriteLine("请输入令狐冲的Java成绩");string sc = Console.ReadLine();double score = double.Parse(sc);

123


二元表达式:

变量=表达式?结果1:结果2;


三、switch结构

语法:

if (score >= 90){ Console.WriteLine("优秀");}else if(score>=75){ Console.WriteLine("良好");}else if (score >= 60){ Console.WriteLine("及格");}else{ Console.WriteLine("不及格");}Console.Read();

456789101112131415161718

string str=txt_score.Text;double score=double.Parse(str);if(score>=90){ lab_level.Text="优秀";}else if(score>=75){ lab_level.Text="良好";}else if(score>=60){ lab_level.Text="及格";}else{ lab_level.Text="不及格";}

1234567891011

int b = 9;/* string a;if (b > 7){ a = "你好";}else{ a = "你渣";}*/string a = b>7?"你好":"你渣";Console.WriteLine(a);Console.Read();

123456789101112


示例3:输入学生的考试名次,第一名:武林盟主,第二名:武当掌门,第三名:峨眉掌门,第四名:逐出师门

示例4:输入年份和月份,判断该月有多少天

switch(表达式){ case 常量1: 语句; break; case 常量2: 语句; break; default 语句}

12345678910

string mingci=txt_mingci.Text;switch(mingci){ case "第一名": MessageBox.Show("武林盟主","比赛结果"); break; case "第二名": MessageBox.Show("武当掌门","比赛结果"); break; case "第三名": MessageBox.Show("峨眉掌门","比赛结果"); break; default: MessageBox.Show("逐出师门","比赛结果"); break;}

123456789101112131415

Console.WriteLine("请输入年份");int y=int.Parse(Console.ReadLine());Console.WriteLine("请输入月份");int m=int.Parse(Console.ReadLine());switch(m){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: Console.WriteLine("有31天","月天数计算"); break; case 4: case 5: case 9: case 11: Console.WriteLine("有30天","月天数计算"); break; case 2: if(y%4==0&&y%100!=0||y%400==0){ Console.WriteLine("有29天","月天数计算"); }else{ Console.WriteLine("有28天","月天数计算"); }

1234567891011121314151617181920212223242526


四、强制类型转换:

int a=9;

double b=a;

double c=888.6;

int d=(int)c;//强制类型转换

string h="123";

//int n=(int)h;//不同类型之间不能进行强制转换

int n=int.Parse(h);

double n=double.Parse(h);

类型转换的流向图

视频课:
https://edu.csdn.net/course/detail/27107

break; default: Console.WriteLine("你输错了","警告"); break;}

2728293031


第三章:循环 什么是循环?

条件:条件成立

循环的操作,

语法

while(条件){

循环操作

}

第一节:while循环

示例1:从1加到100

示例2:循环输入一组学生成绩,求总成绩,当输入成绩为-1时候停止输入。

示例2:循环输入一组学生成绩,求总成绩和平均成绩

int i = 1,sum=0; while (i <= 100) { sum += i; i++; } Console.WriteLine(sum); Console.Read();

12345678

double sum = 0,score = 0;while (score != -1){ Console.WriteLine("请输入学生成绩"); String sco=Console.ReadLine(); score = double.Parse(sco); if (score != -1) { sum += score; }}Console.WriteLine("学生总成绩是:"+sum);

123456789101112

double sum = 0,score = 0,i=0;while (score != -1){ Console.WriteLine("请输入学生成绩"); String sco=Console.ReadLine(); score = double.Parse(sco); if (score != -1) { sum += score; i++; }}

123456789101112


第二节:do-while循环

语法:

do{

循环操作

}while(条件);

示例3:节目彩排

第三节:for循环

语法:

for(变量的初始化 ; 条件判断 ; 变量的变化){

循环操作

}

示例4:从1+...+100

示例5:实现以下效果

Console.WriteLine("学生总成绩是:"+sum);Console.WriteLine("学生平均成绩是:"+sum/i);

1314

string ans = ""; do { Console.WriteLine("欧阳锋弹吉他"); Console.WriteLine("岳不群跳街舞"); Console.WriteLine("张无忌拉提琴"); Console.WriteLine("小尼姑行不行?"); ans = Console.ReadLine(); } while (ans == "不行"); Console.WriteLine("彩排结束");

12345678910

double sum = 0;for(int i=1;i<=100;i++){ sum += i;}Console.WriteLine("1+...+100="+sum);

123456

请输入一个数字:

60+6=61+5=62+4=63+3=64+2=65+1=66+0=6

123456789


第四节:continue和break

continue是继续进行下一次循环的意思,不管continue后面有多少语句都不再执行,而是回到循环条件,进行下一次循环。

示例:6:说数字游戏,输出1~100之间的数字,不能输出明7和暗7

break是结束循环,调到循环结尾,执行之后的代码。


练习:

1、输出从1~100之间能被3整除的数

2、输出从1~100之间的素数

3、输出9*9乘法表

5、猜数游戏,随机给出一个1~100之间的数,给5次机会,每次猜数后给出提示:大了还是小了,猜对后输出成功。获得随机数:

Random rand=new Random(); rand.Next(1,100);

6.编写程序,输出10000—30000中能同时被3、5、7、23整除的数及个数。

7.编写程序,求100—999中的"水仙花"数(也叫阿姆斯特朗数)及个数。(注:若3个数其各个位数字立方和等于该数本身,即为水仙花数,如153=1+125+27,则153是一个"水仙花"数。)

8.编写程序,求2—999中的同构数(也叫自守数)及其个数。(正整数n若是它平方数的尾部,则称n为同构数。例如:5的平方数是25,且5出现在25的右侧,那么5就是一个同构数。)

9.输出1—999中能被3整除且至少有位数字是5的所有整数及其个数。

10.从键盘输入两个正整数m和n,找出它们的最小公倍数。

11.输出Fibonacci数列1,1,2,3,5,8,13,…中前32项的值。

作业:讲解


Console.WriteLine("请输入一个数字");int num = int.Parse(Console.ReadLine());for(int i=0,j=num ;i<=num ; i++, j--){ Console.WriteLine(i+"+"+j+"="+num);}

123456

for(int j = 1; j <= 100; j++){ if (j % 10 == 7 || j / 10 == 7 || j % 7 == 0) { continue; } Console.Write(j+"\t");}Console.ReadLine();

123456789


思路:

不要背代码,第一步:观察九九乘法表有9行;有9列;

第一步能不能把九九乘法表的问题,给分解成先输出9行;


第四章:数组 定义:一组连续的内存空间,保存一组同类型的数据,数组有编号(下标)

第一节:数组的声明和遍历

数据类型[] 数组名称=new 数据类型[5];

数据类型[] 数组名称=new 数据类型[5]{数组的元素};

一、数组的声明和遍历

示例1:

数组一旦创建完毕,它的长度是不能改变的,数组的下标从0开始。最大下标是数组的长度减一。

二、数组的比较大小

示例:2:求学生成绩的最高分(最低分、平均分)

int[] arr=new int[6];string[] names=new string[4]{"王重阳","李逵","张无忌","张三丰"};arr[0] = 6;// arr[6] = 88; 数组下标越界//arr[2]="令狐冲"; 整型数组只能装整型值//Console.WriteLine(names[5]); 数组下标越界//names.Length 数组长度属性:Lengthfor(int i = 0; i < names.Length; i++) //遍历数组中的每一个元素{ Console.WriteLine(names[i]);}

1234567891011


三、查找数组中的元素

示例3:查找指定的数值在数组中的位置

四、数组的删除

示例4:从数组中删除给出的数字

double[] scores = new double[] { 89, 58, 99, 100, 110, 66, 95, 78, 45.6, 98.6, 88 };double max = scores[0]; //让数组的第一个元素站到擂台上for (int i = 1; i < scores.Length; i++){ if (scores[i] > max)//将数组中后面的元素依次和擂台上的数进行比较, { max = scores[i];//比擂台上数字大的站到擂台上 }}Console.WriteLine("学生的最高成绩是:"+max);

1

2345678910

int[] arr = new int[] {4,6,8,9,2,11,33,46 };Console.WriteLine("请输入要查找的数");string str=Console.ReadLine();int num = int.Parse(str);int index = -1;for(int i = 0; i < arr.Length; i++){ if (num == arr[i]) { index = i; break; }}if (index != -1){ Console.WriteLine("你要找的数字"+num+"在下标为"+index+"的位置");}else{ Console.WriteLine("没有找到你要的数"+num);}

1234567891011121314151617181920

int[] arr = new int[] {8,6,9,5,73,11,56,87 };Console.WriteLine("请输入你要删除的元素");int num = int.Parse(Console.ReadLine());int index = -1;for(int i = 0; i < arr.Length; i++){ if (num == arr[i])//查找要删除的元素 { index = i; break; }}if (index != -1){ for(int j = index; j < arr.Length-1; j++)//注意j是要小于arr.length-1; { arr[j] = arr[j + 1];//将从删除位置开始的数组元素依次前移

1234567891011121314151617


示例5:在顺序数组中插入一个数,要求插入后仍然保持数组的升序排列。

视频课:
https://edu.51cto.com/course/20906.html

第五章:类和对象 什么是对象

描述一个对象:

姓名:欧阳锋

性别:男

家住:深圳

。。。。属性;

弹吉他;

跳街舞;

。。。。能力


} arr[arr.Length - 1] = 0;//将数组最后一个元素置成0}else{ Console.WriteLine("没有你要删除的元素");} ///////////for(int i = 0; i < arr.Length; i++){ Console.Write(arr[i]+"\t");}

1819202122232425262728

int[] arr = new int[] { 10, 20, 30, 40, 50, 60 ,0};Console.WriteLine("请输入要插入的数字");int num = int.Parse(Console.ReadLine());int index = arr.Length-1 ;for(int i = 0; i < arr.Length; i++){ if (arr[i] > num) { index = i; break; }}for(int j = arr.Length - 2; j >= index; j--){ arr[j + 1] = arr[j];}arr[index] = num;for (int i = 0; i < arr.Length; i++){ Console.Write(arr[i] + "\t");}

123456789101112131415161718192021


欧阳锋外传——封装

对象:是组成世界万物的具体个体

类:是有相同特点的个体的抽象概念

第一节:创建类和对象

创建类:

创建对象:

在图形界面造人

构造方法:

构造方法是创建该类对象的方法,如果类中没有构造方法,系统会给一个默认(无参数)的构造方法

构造方法的结构是:public 类名(){}

一个类中一般需要有两个构造方法,一个是空参数(默认)的构造方法,一个是带参数的构造方法。

class Person{ public string name; public string sex; public int age; public void intro() { Console.WriteLine("我是:"+name+"性别:"+sex+",今年"+age+"岁了"); }}

12345678910

Person p = new Person();p.name = "令狐冲";p.sex = "男";p.age = 8;Console.WriteLine(p.name);p.intro();

123456

string name = txtName.Text;string sex = txtSex.Text;int age = int.Parse(txtAge.Text);Person per = new Person();per.name = name;per.sex = sex;per.age = age;per.intro();

12345678

public Person(){ }

public Person(string name, string sex, int age) { this.name = name;//this代表当前类的对象 this.sex = sex; this.age = age; }

12345678


第二节:定义一般方法

方法的种类

方法分类:

一、无参数无返回值

二、有参数无返回值

三、无参数有返回值

调用:

四、有参数有返回值

方法调用:

Person p = new Person("张无忌","男",12); Console.WriteLine(p.name); p.intro();

123

public void intro() { Console.WriteLine("我是:"+name+"性别:"+sex+",今年"+age+"岁了"); }

1234

public void playGame(int level){ if (level > 10) { Console.WriteLine("打败boss"); }else { Console.WriteLine("game over"); } }

12345678910

public int getRandom(){ Random ran = new Random(); return ran.Next(0,100); }

12345

Student stu = new Student("王宗月","男",20); stu.intro(); stu.playGame(50); int num=stu.getRandom(); Console.WriteLine("随机数是:"+num); Console.Read();

123456

public double plus(double num1,double num2){ return num1 + num2;}

1234


五、类的完整代码:

练习:1)编写狗类的代码并创建对象进行测试;2)编写手机类代码并测试;

Person per = new Person(); double n1 = double.Parse(txtNum1.Text); double n2 = double.Parse(txtNum2.Text); double result=per.plus(n1,n2); MessageBox.Show(""+result,"计算结果是:");

12345

class Person{ public string name; public string sex; public int age; public void intro()//无参数无返回值 { Console.WriteLine("我是:"+name+"性别:"+sex+",今年"+age+"岁了"); }

public void playGame(int level)//无参数有返回值 { if (level > 10) { Console.WriteLine("打败boss"); }else { Console.WriteLine("game over"); }

}

public double plus(double num1,double num2)//有参数有返回值 { return num1 + num2; }

public string say()//无参数有返回值 { return "欢迎你来到我家"; }

public Person(){ }//默认构造方法

public Person(string name, string sex, int age)//带参数的构造方法 { this.name = name; this.sex = sex; this.age = age; }}

1234567891011121314151617181920212223242526272829303132333435363738394041

class Dog{ public string name; public string sex; public int age; public string color;

123456


测试代码:

电话的类代码:

public Dog() { } public Dog(string name,string sex,int age,string color) { this.name = name; this.sex = sex; this.age = age; this.color = color; }

public void eat(string food) { Console.WriteLine("狗狗"+name+"在吃"+food); }

public string seeDoor(string who) { if (who == "生人") { return "旺旺"; } else { return "摇尾巴"; } }}

789101112131415161718192021222324252627282930313233

Dog dog = new Dog("花花","母",2,"白色");dog.eat("肉骨头");string res=dog.seeDoor("生人");Console.WriteLine(res);

1234

class Phone{ public string brand; public double price; public string type; public Phone() { } public Phone(string brand,double price,string type) { this.brand = brand; this.price = price; this.type = type; } public void listenMusic() { Console.WriteLine(brand+type+"手机在播放音乐"); }

public double comp(double num1,double num2,string opt) { if (opt == "+") return num1 + num2; if (opt == "-") return num1 - num2;

123456789101112131415161718192021


手机测试代码:


第三节:系统常用类ArrayList (集合)

第四节:ListBox和combobox控件的使用

两者都有集合items属性,是用来装内容的,其本质是ArrayList集合,添加ListBox组件将items添加名字等字符串,实现如下效果,点击按钮将ListBox中的所有项添加到comboBox中。

if (opt == "*") return num1 * num2; if (opt == "/") return num1 / num2; return 0; }

public void call(string phoneCode) { Console.WriteLine("给"+phoneCode+"号码打电话"); }

public string reportTime() { return DateTime.Now.ToString(); }}

222324252627282930313233343536

Phone p = new Phone("华为",4560,"荣耀T-5");p.listenMusic();Console.WriteLine(p.reportTime());p.call("13526985241");Console.WriteLine(p.comp(6.5,5.9,"*"));

12345

ArrayList list = new ArrayList(); list.Add(new Person("任我行", "男", 58));//向集合中添加元素 list.Add(new Person("任盈盈", "女", 18)); list.Add(new Person("令狐冲", "男", 18)); list.Add(new Person("东方不败", "不男不女", 18)); list.Add(new Person("岳不群", "不男不女", 48)); Console.writeLine(list.Count);//打印集合中元素的数量 list.RemoveAt(3);//删除索引位置为3 的元素 list.Insert(2,new Person("鹿晗","女",23));//在指定索引位置插入元素 foreach (Person per in list) { Console.WriteLine(per.name+":"+per.sex+":"+per.age); } list.Clear();//清空集合中所有的元素

123456789101112131415


1、单个添加的代码

欢迎按钮代码:

将文本框内容单个添加到LIstBox中的按钮的代码:

将ListBox中内容单个添加到comboBox中的代码:

2、将ListBox中选中的所有项一起移动到comboBox中的代码

改变ListBox中的selectionMode属性为multiSimple让ListBox中的选项可以多选。

string name = txtName.Text;MessageBox.Show("欢迎你:"+name,"提示");

12

string name = txtName.Text;listNames.Items.Add(name);txtName.Text = "";

123

string name = (string)listNames.SelectedItem;cobName.Items.Add(name);cobName.SelectedIndex = 0;listNames.Items.RemoveAt(listNames.SelectedIndex);

1234

foreach(string item in list.Items)//将ListBox集合中所有的元素遍历{ cob.Items.Add(item);//将遍历的每一个集合元素添加到comboBox集合中}cob.SelectedIndex = 0;//让comboBox集合中默认选中第一个元素list.Items.Clear();//清空ListBox集合中所有元素

123456


第三节:类的静态属性和方法—static

Person per=new Person();

per.intro();

类的属性或方法一旦定义了静态:static,该变量就不能被实例对象访问,只能通过类名直接访问。

示例1:

调用的时候

类的ToString()方法:

foreach(string sel in list.SelectedItems)//遍历ListBox中选中元素的集合{ cob.Items.Add(sel);//将选中元素添加到comboBox中}cob.SelectedIndex = 0;while (list.SelectedItems.Count > 0){ list.Items.Remove(list.SelectedItems[0]);//从ListBox大集合Items中删除选中集合中的每一个元素,因为删除后集合会自动前移,所以只需要删除第一个元素即可。

}

12345678

9

class Student { public string name; public string sex; public int age; public static string className; public Student(string name,string sex,int age) { this.name = name; this.sex = sex; this.age = age; }

public void intro() { Console.WriteLine("我是:"+name+",性别"+sex+",今年"+age+"岁"+"在"+className); }

public static void testc() { Console.WriteLine("nihao helloworld"); }}

12345678910111213141516

17181920212223

Student stu3 = new Student("周钦荣", "男", 20); //stu3.className = "java2班";//这样调用是不行的 Student.className="java3班"; Student.testc();

1234


控制台输出:窗体程序需要在项目中右键—【属性】—【输出类型】—【控制台应用程序】


第六章:winform界面

第一节:名词解释

partial:部分的,指目前创建的类为部分类,只有当两个partial类合在一起才能起到应有的作用:

Form:窗体类,其中Form1 : Form是继承的意思

第二节:窗体的属性

name : btn_plus,txt_num1

text: 界面上显示的文本

backgroundimage: 添加背景图片

FormBorderStyle: FixedSingler,定义边界可否改变

maxinimizeBox: 最大化按钮

StartPosition:窗体起始位置

WindowState:窗体初始化的状态,最小化、一般状态、最大化状态

获得文本框的值:txt_num1.Text

转换成数字:int.Parse(txt_num1.Text);double.Parse(txt_num1.Text)


第三节:窗体的事件

click;load;FormClosing; keyDown;

第四节:常用控件

Button

TextBox

RadioButton

DateTimePicker

overridepublic string ToString(){ return "我是:"+name + ":性别" + sex + ":年龄" + age;}

12345

string name = txtName.Text;int age = int.Parse(txtAge.Text);string sex = radMan.Checked ? "男" : "女";Person per = new Person(name, sex, age);Console.WriteLine(per);

12345


dateTimePicker1.Value = DateTime.Parse("2010-10-29");

Panel布局面板,Dock属性

三元表达式:

变量=表达式?第一个值:第二个值;

Timer和PictureBox

示例:实现Tomcat动画,原理就是在PictureBox中每间隔100毫秒加载一次图片,让图片框中显示动画效果。

代码:

/*if (radMan.Checked == true) { sex = "男"; } else { sex = "女"; }*/ //string sex = radMan.Checked?"男":"女"; MessageBox.Show(radMan.Checked ? "男":"女");

12345678910


第五节:消息对话框

MessageBox.Show("内容信息","标题",MessageBoxButton.YesNo,MessageBoxIcon.Question);

MessageBox的返回值:DialogResult.OK;Cancel;Yes;No

第五节:菜单

1、固定菜单:MenuStrip

private void btn_start_Click(object sender, EventArgs e){ timer1.Start();}int count = 0;private void timer1_Tick(object sender, EventArgs e){ picbox.Image = Image.FromFile("angry/angry_"+count+".jpg");//获得文件中的图片 count++; if (count > 25) { count = 0; }}private void button1_Click(object sender, EventArgs e){ timer1.Stop();}

123456789101112131415161718

DialogResult res= MessageBox.Show("你真的要退出程序么?","提示", MessageBoxButtons.YesNo,MessageBoxIcon.Question); if (res == DialogResult.Yes) { e.Cancel = false; } else { e.Cancel = true; }

12345678910


2、右键菜单:ContextMenuStrip

第四节:界面传值

要打开的窗体代码

第一个窗体中打开第二个窗体的代码

第五节:运行指定窗体

测试或练习时经常要直接运行某一个窗体,如果从菜单处一级级打开太麻烦,可以直接修改主程序代码来完成。

修改Main中最后一句代码:Application.Run(new Form1());将Run()中的窗体换成要运行的窗体就可以了。

第六节:主从窗体

主窗体的isMdiContainer属性设置成true,在打开子窗体的代码中,设置子窗体的MdiParent=this;

public partial class Form2 : Form{ public string name;//在要打开的页面中声明一个共有的变量用来接收数据 public Form2() { InitializeComponent(); }

private void Form2_Load(object sender, EventArgs e)//窗体加载事件 { labName.Text = name;//将接收到的数据在labName标签上显示 }}

12345678910111213

Form2 form = new Form2();form.name = txtName.Text;//将本窗体文本框的文本值赋值给要打开窗体的共有属性nameform.Show();

123

Form2 fm = new Form2();fm.Show();fm.MdiParent = this;

123


视频课:
https://edu.51cto.com/course/20906.html

第七章:连接数据库

第一节:ADO.NET的结构

数据库访问的顺序:

1)建立数据库连接

2)打开数据库连接

3)编写SQL语句

4)创建SQL命令对象SQLCommand

5)执行SQL命令

6)关闭数据库连接


示例1:添加班级信息

string constr="server=localhost;userid=root;password=root; database=school";MySqlConnection conn = new MySqlConnection(constr);//创建数据库连接对象conn.Open();//打开连接对象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);//根据sql命令和数据库连接创建数据库命令对象

int count=command.ExecuteNonQuery();//执行数据库的非查询命令if (count > 0)//如果返回值(影响的行数)大于0,提示录入成功{ MessageBox.Show("班级录入成功");}conn.Close();//关闭数据库连接

123456

7

8910111213


第二节:DataSet结构

1)数据集合的作用:是在内存中建立起一个临时的数据仓库,可以对其进行操作并同步到底层数据库。

2)数据集结构:


3)使用DataTable

有行和列的集合:Columns和Rows,

Rows就是查询获得的数据表中的每一行数据集合,集合就可以通过索引或下标访问,例如:通过Rows【1】【"班级名称" 】获得该数据,

Columns是表格中列的集合,通过Columns【"身份证号码"】来获得指定的列对象

4)DataGridView

常用属性:

DataSource:数据源,可以设置某一个DataTable即可

SelectionMode:是表格的选择模式,一般选择FullRowSelect

MultiSelect:是否可以多选

ReadOnly:是否只读

添加该控件后顺手把它的这几个选项如图选定,一般不在表格中进行添加和修改操作。


示例2:数据查询

查询使用数据适配器MySQLDataAdapter,用法和MySqlCommand相同,该适配器可以填充一个内存中的表格DataTable对象,然后让dataGradView的数据源(DataSource)指向该表格。

示例3:数据库通用代码

string connstr = "server=localhost;userid=root;password=root; database=school";MySqlConnection conn = new MySqlConnection(connstr);string sql ="select buildId 宿舍楼编号,buildName 宿舍楼名称 from building ";//查询宿舍楼的所有信息

MySqlDataAdapter adapter = new MySqlDataAdapter(sql,conn);//创建数据适配器DataTable dt = new DataTable();//创建内存中数据表格adapter.Fill(dt);//使用适配器将查询后的数据填充到内存的数据表中dgvBuild.DataSource = dt;//将dataGradView的数据源指向内存中的数据表

123

45678

class DBHelper{ public static string constr = "server=localhost;user id=root; password=root; database=school"; public static MySqlConnection getConnection() { MySqlConnection conn = new MySqlConnection(constr); conn.Open(); return conn; }

public static void close(MySqlConnection conn) { if (conn != null) { conn.Close(); conn = null; } }

public static int update(string sql) {

123

456789101112131415161718192021


示例3:使用通用类的方法完成添加和查询

示例4:使用通用方法完成向comboBox中添加班级信息

示例5:将班级对象加入到comboBox中

创建Classes类

MySqlConnection conn = getConnection(); MySqlCommand command = new MySqlCommand(sql, conn); int count = command.ExecuteNonQuery(); conn.Close(); return count; }

public static DataTable query(string sql) { MySqlConnection conn = getConnection(); DataTable dt = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(sql,conn); adapter.Fill(dt); return dt; }}

22232425262728293031323334353637

string className = txtClassName.Text;string createDate = dtpCreateClasses.Text;string sql = string.Format()"insert into classes(className,createDate) values('{0}','{1}')",className,createDate);DBHelper.update(sql);sql = "select classId 班级编号,className 班级名称,createDate 开班日期 from classes order by classId desc";DataTable dt = DBHelper.query(sql);dgvClass.DataSource = dt;

123

45

678

string sql = "select classId,className from classes";DataTable dt = DBHelper.query(sql);//MessageBox.Show(dt.Rows[0]["className"].ToString()); foreach(DataRow row in dt.Rows){//rows是dataTable的行的集合,可以通过下标来访问 combDormType.Items.Add(row["className"].ToString());}//某一行中有sql中查询的字段信息可以通过dt.Rows[i]["字段名"]来访问
combDormType.SelectedIndex = 0;//设置下拉框默认选中第一个选项

12345678

class Classes{ public int classId; public string className;

public Classes(int classId,string className) { this.classId = classId; this.className = className; } public Classes() { }

override//表示该方法是覆盖父类的方法,用来显示该类的对象

12345678910111213


示例6:改造加入comboBox的代码,将classes对象加入到comboBox中

示例7:测试comboBox中选中的对象的classId和className 数据,在comboBox的selectedIndexChange事件中执行如下代码:

视频课:
https://edu.51cto.com/course/20906.html

第八章:数据修改 数据修改不能直接像录入一样在界面填入数据,只能先查询出数据,选定某条数据后点击修改按钮,将该条数据显示在一个类似于录入界面的窗体中再进行修改,修改过的数据再点击确定最后修改到数据库,需要的话再刷新查询数据。

一、查询出班级数据

二、点击修改按钮、创建修改窗体

示例 1:

public string ToString() { return className; }}

1415161718

DataTable dt = DBHelper.query("select * from classes");foreach(DataRow row in dt.Rows){ Classes cla = new Classes((int)row[0],row[1].ToString()); combClass.Items.Add(cla);//将classes对象放入到组合框中}combClass.SelectedIndex = 0;

1234567

Classes cla = (Classes)combDormType.SelectedItem;MessageBox.Show(cla.classId+":"+cla.className);

123


三 、在修改窗体的load事件中根据传进来的classId查询班级信息,并将班级信息填入相应的组件中。

四、在修改窗体中点击修改按钮

五、学生入住

string classId = dgvClass.SelectedRows[0].Cells[0].Value.ToString();//获得表格中选中的第一行的第一个单元的值,付给classId;FmClassUpdate fcu = new FmClassUpdate();fcu.classId = classId;//给FMClassUpdate窗体中的classId属性赋值fcu.ShowDialog();//以模态窗体的形式显示修改窗体fcu.MdiParent = this.MdiParent;//将修改窗体的父窗体设置为主窗体

1

2345

string sql = "select className,createDate from classes where classId="+classId;DataTable dt = DBHelper.query(sql);txtClassName.Text= dt.Rows[0]["className"].ToString();//给文本框赋值成查询的班级名称dtpClassDate.Value =(DateTime)dt.Rows[0]["createDate"];

1234

string sql = string.Format("update classes set className='{0}', createDate='{1}' where classId={2}",txtClassName.Text,dtpClassDate.Text , classId);int count = DBHelper.update(sql);if (count > 0){ Close();}else{ MessageBox.Show("修改错误","提示");}

1

23456789


界面中按照班级查询出要入住的学生,在左侧选定要进入的宿舍,选定入住的学生(多选)点击入住完成操作,如果选中的人数大于可以入住的空位,则要提示人数太多,

学生按条件查询,如果没有输入条件则按照所有的查询

//获得左边选中宿舍的编号,注意宿舍编号列是隐藏的在第一位cells[0]string dormId = dgvDorm.SelectedRows[0].Cells[0].Value.ToString() ;string stuId = "";string sql = "";//获得目前该宿舍中已经入住的人数,以便判断选中的学生人数是否超过该宿舍的额定人数sql = "select count(*) dormCount from student where fk_dormId="+dormId;DataTable dtCount = DBHelper.query(sql);//Console.WriteLine(dtCount.Rows[0]);int dormCount =int.Parse( dtCount.Rows[0].ToString());//查询该宿舍最多能住的人数sql = "select perCount from dorm,dormType where fk_dormTypeId=typeId and dormId="+dormId;DataTable dtPerCount = DBHelper.query(sql);int perCount = (int)dtPerCount.Rows[0];if (perCount - dormCount >=
dgvStudent.SelectedRows.Count){ for(int i = 0; i <
dgvStudent.SelectedRows.Count; i++) {//将选中的学生逐个加入到选定的宿舍(修改学生的宿舍外键为该宿舍的) stuId = dgvStudent.SelectedRows[i].Cells["编号"].Value.ToString(); sql = string.Format("update student set fk_dormId={0} where stuId={1}",dormId,stuId); DBHelper.update(sql); } //将该宿舍中已经有的学生显示到dgvDormStudent表格中 sql = "select stuId 学生编号,stuName 学生姓名 from student where fk_dormId="+dormId; DataTable dt = DBHelper.query(sql); dgvDormStudent.DataSource = dt; btnStuQuery_Click(sender, e);//调用学生查询按钮的方法}else{ MessageBox.Show("宿舍住不下这么多人,请重新选择!","提示");}

1234567891011

1213141516171819

20212223

24252627282930

public void queryStudent()1


{ string sql = "select stuId, stuName 姓名,student.sex 性别,idcard 身份证,telPhone 电话,city 城市,className 班级,dormName 宿舍 from student join classes on classId=fk_classId left join dorm on fk_dormId=dormId"; if (txtName.Text != "") { sql += string.Format(" and stuName like '%{0}%'", txtName.Text); } if (txtClassName.Text != "") { sql += string.Format(" and className like '%{0}%'", txtClassName.Text); } if (txtCity.Text != "") { sql += string.Format(" and city = '{0}'", txtCity.Text); } dgvStudent.DataSource = DBHelper.query(sql); dgvStudent.Columns["身份证"].Width = 200;//让身份证那一列宽度加大 dgvStudent.Columns["stuId"].Visible = false;//让学生编号列隐藏}

23

45678910111213141516171819


  • C#WinForm基础编程
    • 第一章:C#基础入门
      • 第一节:数据类型和变量
        • 一、数据类型:
          • 基本数据类型
          • 扩展数据类型
        • 二、声明变量:
          • 变量赋值:
          • 变量命名:
  • 第二章:判断
    • 一、单个if-else
    • 二、多重if-else
      • 判断学生成绩的等级
      • 二元表达式:
    • 三、switch结构
    • 四、强制类型转换:
      • 类型转换的流向图
    • 视频课:https://edu.csdn.net/course/detail/27107
  • 第三章:循环
    • 什么是循环?
    • 语法
    • 第一节:while循环
    • 第二节:do-while循环
    • 第三节:for循环
    • 第四节:continue和break
    • 练习:
  • 第四章:数组
    • 第一节:数组的声明和遍历
      • 一、数组的声明和遍历
      • 二、数组的比较大小
    • 视频课:https://edu.51cto.com/course/20906.html
  • 第五章:类和对象
    • 什么是对象
      • 对象:是组成世界万物的具体个体
      • 类:是有相同特点的个体的抽象概念
    • 第一节:创建类和对象
      • 创建类:
      • 创建对象:
      • 构造方法:
    • 第二节:定义一般方法
    • 方法的种类
      • 一、无参数无返回值
      • 二、有参数无返回值
      • 三、无参数有返回值
      • 四、有参数有返回值
    • 第三节:系统常用类ArrayList (集合)
    • 第四节:ListBox和combobox控件的使用
      • 1、单个添加的代码
      • 2、将ListBox中选中的所有项一起移动到comboBox中的代码
    • 第三节:类的静态属性和方法—static
      • 类的ToString()方法:
  • 第六章:winform界面
    • 第一节:名词解释
    • 第二节:窗体的属性
    • 第三节:窗体的事件
    • 第四节:常用控件
      • 三元表达式:
    • 第五节:消息对话框
    • 第五节:菜单
    • 第四节:界面传值
    • 第五节:运行指定窗体
    • 第六节:主从窗体
    • 视频课:https://edu.51cto.com/course/20906.html
  • 第七章:连接数据库
    • 第一节:ADO.NET的结构
      • 数据库访问的顺序:
    • 第二节:DataSet结构
    • 视频课:https://edu.51cto.com/course/20906.html
  • 第八章:数据修改

Tags:

最近发表
标签列表