.NET 程序设计实验 含记事本通讯录代码
实验一 .NET 程序设计基本流程
【实验内容】
一、控制台、Windows 应用程序、ASP.NET 程序开发流程
1、熟悉开发平台
2、分别开发控制台、Windows 应用程序、ASP.NET 程序下显示“Hello world!”的应用程序, 掌握新建、基本输入输出、程序流程、程序调试的过程。
控制台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace he
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
}
}
Windows 应用程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Helllo world ";
}
}
}
ASP.NET 程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "Hello yun";
}
}
}
第二部分面向对象编程
实验一 类和对象编程
一、类的定义
1、编写一个控制台应用程序,定义并使用一个时间类,该类包含时、分、秒字段与属 性,具有将时间增加 1 秒、1 分和 1 小时的方法,具有分别显示时、分、秒和同时显示 时分秒的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Time
{
private int h;
private int m;
private int s;
public int H
{
get
{
return h;
}
set
{
h = value;
}
}
public int M
{
get
{
return m;
}
set
{
m = value;
}
}
public int S
{
get
{
return s;
}
set
{
s= value;
}
}
public void adds()
{
s++;
if (s > 60)
{
m++;
s = s % 60;
}
if (m > 60)
{
h++;
m = m % 60;
}
if (h > 24)
{
h = h % 24;
}
}
public void addm()
{
m++;
if (m > 60)
{
h++;
m = m % 60;
}
if (h > 24)
{
h = h % 24;
}
}
public void addh()
{
h++;
if (h > 24)
{
h = h % 24;
}
}
public void disph()
{
Console.WriteLine("现在时为:{0}", h);
}
public void dispm()
{
Console.WriteLine("现在分为a:{0}", m);
}
public void disps()
{
Console.WriteLine("现在秒为:{0}", s);
}
public void dispt()
{
Console.WriteLine("现在时间为:{0}:{1}:{2}:", h, m, s);
}
}
public class text
{
public static void Main()
{
Time time = new Time();
time.H = DateTime.Now.Hour;
time.M = DateTime.Now.Minute;
time.S = DateTime.Now.Second;
time.dispt();
Console.WriteLine("增加1秒");
time.adds();
time.dispt();
Console.WriteLine("增加1分");
time.addm();
time.dispt();
Console.WriteLine("增加1时");
time.addh();
time.dispt();
Console.WriteLine("分别输出时分秒:");
time.disph();
time.dispm();
time.disps();
}
}
}
2.编写一个控制台应用程序,程序中有两个类定义,一个是创建程序时系统自动创建 的类 Class1,一个是用户自定义的Student 类,要求该类包含私有字段:学号(字符串)、姓名(字符 串)和性别(字符),具有三个属性:学号(读写)、姓名(只读)、性别(读写), 具有有参构造方法、具有同时显示学生个人信息的方法。在 Class1 类的 Main 方法中完 成以下功能: 1)从键盘上输入一个学生的个人信息(学号、姓名、性别)。 2)修改该学生的学号和性别。 3)打印修改前后该学生的个人信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Student
{
private string num;
private string name;
private char sex;
public string Num
{
get
{
return num;
}
set
{
num = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public char Sex
{
get
{
return sex;
}
set
{
sex = value;
}
}
public Student()
{
Console.WriteLine("请输入学号、 姓名、 性别:");
num = Console.ReadLine();
name = Console.ReadLine();
sex = Convert.ToChar(Console.ReadLine());
}
public void Re()
{
Console.WriteLine("修改学号:");
num = Console.ReadLine();
Console.WriteLine("修改性别:");
sex = Convert.ToChar(Console.ReadLine());
}
public void print()
{
Console.WriteLine("学号:{0},姓名:{1},性别:{2}", num, name, sex);
}
}
public class text
{
public static void Main()
{
Student student1 = new Student();
Console.WriteLine("学生信息:");
student1.print();
Console.WriteLine("修改信息");
student1.Re();
Console.WriteLine("学生信息:");
student1.print();
}
}
}
3.编写一个控制台应用程序,程序中有两个类定义,一个是创建程序时系统自动创建 的类 Class1,一个是用户自定义的 Student 类,要求该类包含私有实例字段:学号(字 符串)、姓名(字符串)、成绩(double)以及私有静态字段:学生人数、学生总 成绩、学生平均成绩,具有有参构造方法、显示学生个人信息的公有实例方法和显示学生人数、 总成绩及平均成绩的公有静态方法。在 Class1 类的 Main 方法中完成以下功能: 1)从键盘上依次输入三个学生的个人信息(学号、姓名、成绩)。 2)统计全部学生的人数、总成绩和平均成绩。 3)打印学生们的个人信息及全部学生的人数、总成绩和平均成绩。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
private string num;
private string name;
private double score;
public static int count;
public static double sum;
public static double average;
public Student()
{
Console.WriteLine("请输入学生信息:");
Console.WriteLine("学号:");
num = Console.ReadLine();
Console.WriteLine("姓名:");
name = Console.ReadLine();
Console.WriteLine("成绩:");
score = Convert.ToDouble(Console.ReadLine());
sum += score;
count++;
}
public static void Average()
{
average=sum/count;
}
public void dispinfo()
{
Console.WriteLine("学号:{0},姓名:{1},成绩:{2}", num, name, score);
}
public void dispsc()
{
Console.WriteLine("学生人数:{0}", count);
Console.WriteLine("学生总成绩:{0}", sum);
Console.WriteLine("学生平均成绩:{0}", average);
}
}
public class Text3
{
public static void Main()
{
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student.Average();
s1.dispinfo();
s2.dispinfo();
s3.dispinfo();
s1.dispsc();
}
}
}
实验二 继承与多态编程
1、创建一个描述图书信息的类并测试。类中应保存有图书的书号、标题、作者、出版社、 价格等信息。 1)定义图书类 Book,Book 类中包含 isbn(书号)、title(标题)、author(作者)、press (出版社)、price(价格)等私有字段。由于对一本书来说,书号是唯一的,因此,isbn 字段应声明为只读的。 2)为 Book 类中的每个字段定义相应的属性,由于 isbn 字段只读的,其相应属性也应 该是只读的。 3)为 Book 类定义两个构造函数,其中,一个构造函数将所有字段都初始化为用户指定 的值,另一个构造函数只要求用户指定有关书号的信息,它将调用上一个构造函数初始化对 象,初始化时,价格取 0,除书号的其他信息取“未知”。 4)为 Book 类定义方法 Show,Show 方法用于显示图书的所有信息。 5)编写 Main 方法测试 Book 类,Main 方法中分别使用上述两个构造函数创建 Book 对 象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class book
{
private readonly string isbn;
private string title;
private string author;
private string press;
private double price;
public string Isbn
{
get
{
return isbn;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public string Author
{
get
{
return author;
}
set
{
Author = value;
}
}
public string Press
{
get
{
return press;
}
set
{
Press = value;
}
}
public double Price
{
get
{
return price;
}
set
{
Price = value;
}
}
public book(string isbn, string title, string author, string press, double price)
{
this.isbn = isbn;
this.title = title;
this.author = author;
this.press = press;
this.price = price;
}
public book(string isbn) : this(isbn, "未知", "未知", "未知",0)
{ }
public void Show()
{
Console.WriteLine("书信息:");
Console.WriteLine("书号:{0}", isbn);
Console.WriteLine("标题:{0}", title);
Console.WriteLine("作者:{0}", author);
Console.WriteLine("出版社:{0}", press);
Console.WriteLine("价格:{0}", price);
}
}
class Test
{
public static void Main()
{
Console.WriteLine("请输入书的信息(书号,标题,作者,出版社,价格)");
book b1 = new book(Convert.ToString(Console.ReadLine()), Convert.ToString(Console.ReadLine()), Convert.ToString(Console.ReadLine()), Convert.ToString(Console.ReadLine()), Convert.ToDouble(Console.ReadLine()));
b1.Show();
Console.WriteLine("请输入书号:");
book b2 = new book(Convert.ToString(Console.ReadLine()));
b2.Show();
}
}
}
2、编写一个程序计算出球、圆柱和圆锥的表面积和体积。 1)定义一个基类圆,至少含有一个数据成员:半径; 2)定义基类的派生类:球、圆柱、圆锥,都含有求体积函数,可以都在构造函数中实 现,也可以将求体积和输出写在一个函数中,或者写在两个函数中,请比较使用。 3)定义主函数,求球、圆柱、圆锥的和体积。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Circle
{
protected double R;
public const double PI = 3.14;
}
public class Ball : Circle
{
protected double Vol;
protected double Area;
public Ball(double r)
{ R = r; }
public double GetArea()
{
Area = 4 * PI * R * R;
return Area;
}
public double GetVol()
{
Vol = (4.0 / 3.0) * PI * R * R * R;
return Vol;
}
public void Print()
{
Console.WriteLine("球的表面积为:{0}", Area);
Console.WriteLine("球的体积为:{0}", Vol);
}
}
public class Cyl : Circle
{
protected double Vol;
protected double Area;
protected double h;
public Cyl() { }
public Cyl(double r, double h)
{
R = r;
this.h = h;
}
public virtual void GetArea()
{
Area = h * 2 * PI * R + 2 * PI * R * R;
Console.WriteLine("圆柱的表面积为:{0}", Area);
}
public virtual void GetVol()
{
Vol = h * PI * R * R;
Console.WriteLine("圆柱的体积为:{0}", Vol);
}
}
public class Cone : Cyl
{
public Cone(double r, double h)
{
R = r;
this.h = h;
}
public override void GetArea()
{
Area = PI * R * R + 0.5 * 2 * PI * R * System.Math.Sqrt(R * R + h * h);
Console.WriteLine("圆锥的表面积为:{0}", Area);
}
public override void GetVol()
{
Vol = (1.0 / 3.0) * h * PI * R * R;
Console.WriteLine("圆锥的体积为:{0}", Vol);
}
}
class Test
{
public static void Main()
{
Console.WriteLine("请输入球半径");
double count = Convert.ToDouble(Console.ReadLine());
Ball ball = new Ball(count);
double A = ball.GetArea();
double V = ball.GetVol();
ball.Print();
Console.WriteLine("请输入圆柱半径和高");
Cyl cyl = new Cyl(Convert.ToDouble(Console.ReadLine()), Convert.ToDouble(Console.ReadLine()));
cyl.GetArea();
cyl.GetVol();
Console.WriteLine("请输入圆锥半径和高");
Cone cone = new Cone(Convert.ToDouble(Console.ReadLine()), Convert.ToDouble(Console.ReadLine()));
cone.GetArea();
cone.GetVol();
}
}
}
3、设计一个图书卡片类 Card,用来保存图书馆卡片分类记录。 1)这个类的成员包括书名、作者、馆藏数量。 2)至少提供两个方法,store 书的入库处理,show 显示图书信息。 3)程序运行时,可以从控制台上输入需要入库图书的总量,根据这个总数创建 Card 对象数组,然后输入数据。 4)可以选择按书名、作者、入库量进行排序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Card
{
private string name;
public string Name
{
get
{
return name;
}
}
private string author;
public string Author
{
get
{
return author;
}
}
private int num = 0;
public int Num
{
get
{
return num;
}
}
public void Store()
{
Console.WriteLine("输入书的信息(书名 作者 入库量)");
this.name = Convert.ToString(Console.ReadLine());
this.author = Convert.ToString(Console.ReadLine());
this.num = Convert.ToInt32(Console.ReadLine());
Library.Num += num;
}
public void Show()
{
Console.WriteLine("图书馆信息:");
Console.WriteLine("书名:{0},作者:{1},馆藏数量{2}", name, author, num);
}
}
public class Library
{
public static int Num = 0;
public static void Show()
{
Console.WriteLine("图书馆共入库{0}本书", Num);
}
}
public class Test
{
public static void Main()
{
int i; int type;
Card temp;
Console.WriteLine("请输入入库图书量:");
type = Convert.ToInt32(Console.ReadLine());
Card[] card = new Card[type];
for (i = 0; i < type; i++)
{
card[i] = new Card();
card[i].Store();
}
Library.Show();
Console.WriteLine("请选择排序:1、书名,2、作者,3、库存量");
int a = Convert.ToInt32(Console.ReadLine());
switch (a)
{
case 1:
{
Console.WriteLine("按书名从小到大排序");
for (i = 0; i < 2; i++)
{
for (int j = i; j < 3; j++)
{
if (string.Compare(card[i].Name, card[j].Name) > 0)
{
temp = card[i];
card[i] = card[i + 1];
card[i + 1] = temp;
}
}
}
for (i = 0; i < 3; i++)
{
card[i].Show();
}
}
break;
case 2:
{
Console.WriteLine("按作者从小到大排序");
for (i = 0; i < 2; i++)
{
for (int j = i; j < 3; j++)
{
if (string.Compare(card[i].Author, card[j].Author) > 0)
{
temp = card[i];
card[i] = card[i + 1];
card[i + 1] = temp;
}
}
}
for (i = 0; i < 3; i++)
{
card[i].Show();
}
}
break;
case 3:
{
Console.WriteLine("按库存量从小到大排序");
for (i = 0; i < 2; i++)
{
for (int j = i; j < 3; j++)
{
if (card[i].Num - card[j].Num > 0)
{
temp = card[i];
card[i] = card[i + 1];
card[i + 1] = temp;
}
}
}
for (i = 0; i < 3; i++)
{
card[i].Show();
}
}
break;
default:
Console.WriteLine("输入错误");
break;
}
}
}
}
二、 类的多态性练习
1、设计雇员系统。 1)定义雇员基类,共同的属性,姓名、地址和出生日期;2)派生类:程序员,秘书,高层管理,清洁工,他们有不同的工资算法,其中高级主 管和程序员采用底薪加提成的方式,高级主管和程序员的底薪分别是 5000 元和 2000 元 , 秘书和清洁工采用工资的方式,工资分别是 3000 和 1000,以多态的方式处理程序。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class Employee
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
string address;
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
string birth;
public string Birth
{
get
{
return birth;
}
set
{
birth = value;
}
}
double salary;
public virtual double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
double royalty;
public virtual double Royalty
{
get
{
return royalty;
}
set
{
royalty = value;
}
}
public virtual void SumSalary() { }
public virtual void Show() { }
}
public class Programmer : Employee
{
public Programmer()
{
Salary = 2000;
Console.WriteLine("请输入程序员提成");
Royalty = Convert.ToDouble(Console.ReadLine());
}
public override void SumSalary()
{
Salary += Royalty;
}
public override void Show()
{
Console.WriteLine("程序员总工资为{0}", Salary);
}
}
public class Secretary : Employee
{
public Secretary()
{
Salary = 3000;
}
public override void Show()
{
Console.WriteLine("秘书总工资为{0}", this.Salary);
}
}
public class Manager : Employee
{
public Manager()
{
Salary = 5000;
Console.WriteLine("请输入高层管理提成");
Royalty = Convert.ToDouble(Console.ReadLine());
}
public override void SumSalary()
{
Salary += Royalty;
}
public override void Show()
{
Console.WriteLine("高层管理总工资为{0}", Salary);
}
}
public class Cleaner : Employee
{
public Cleaner()
{
Salary = 1000;
}
public override void Show()
{
Console.WriteLine("清洁工总工资为{0}", this.Salary);
}
}
class Test
{
public static void Main()
{
Programmer p = new Programmer();
p.SumSalary();
p.Show();
Manager m = new Manager();
m.SumSalary();
m.Show();
Secretary s = new Secretary();
s.Show();
Cleaner c = new Cleaner();
c.Show();
}
}
}
实验三 接口编程
一、分析实现接口的程序文件
分析以下实现接口的程序文件并回答问题:
using System;
public interface IComparable
{
int CompareTo(IComparable comp);
}
public class TimeSpan : IComparable
{
private uint totalSeconds;
public TimeSpan()
{
totalSeconds = 0;
}
public TimeSpan(uint initialSeconds)
{
totalSeconds = initialSeconds;
}
public uint Seconds
{
get
{
return totalSeconds;
}
set
{
totalSeconds = value;
}
}
public int CompareTo(IComparable comp)
{
TimeSpan compareTime = (TimeSpan) comp;
if(totalSeconds > compareTime.Seconds) return 1;
elseif(compareTime.Seconds == totalSeconds) return 0;
else
return -1;
}
}
class Tester
{
public static void Main()
{
TimeSpan myTime = new TimeSpan(3450); TimeSpan worldRecord = new TimeSpan(1239);
if(myTime.CompareTo(worldRecord) < 0) Console.WriteLine("My time is below the world record");
elseif(myTime.CompareTo(worldRecord) == 0) Console.WriteLine("My time is the same as the world record");
else
Console.WriteLine("I spent more time than the world record holder");
}
}
本程序中的接口包含方法的构成是哪些;
int CompareTo(IComparable comp);
实现接口的类包含哪些元素?
private uint totalSeconds;
public TimeSpan()
public TimeSpan(uint initialSeconds)
public uint Seconds
public int CompareTo(IComparable comp)
类实现接口方法的参数如何变换实现的?
public int CompareTo(IComparable comp)
{
TimeSpan compareTime = (TimeSpan) comp;
if(totalSeconds > compareTime.Seconds) return 1;
elseif(compareTime.Seconds == totalSeconds) return 0;
else
return -1;
}
}
给出程序的输出结果。
实验四 委托编程
一、委托及其方法的实现程序
1、程序功能:定义一个含有两个整型参数名叫 Calculation 返回类型为 double 的委托,分 别实现两个匹配的求和、求平均值的方法,并在主函数中测试它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public delegate double Calculation(double a, double b);//定义委托类
class Text
{
public double plus(double a, double b)
{
double val = a + b;
return val;
}
public double aver(double a, double b)
{
double c = ((a + b) / 2);
return c;
}
}
class Test2
{
public static void Main()
{
Text t = new Text();
Calculation c1 = new Calculation(t.plus);
Console.WriteLine("两个数之和为:" + c1(2.9, 6.9));
Calculation c2 = new Calculation(t.aver);
Console.WriteLine("两个数平均值为:" + c2(3.33, 0.29));
}
}
实验五 异常处理编程
一、异常处理
1、设计类,实现异常处理。 1)建立一个名字为 Meteorologist 的类,其中含有一个 12 个 int 类型元素的数组 rainfall,通过构造函数给赋值;一个方法头为 public int GetRainfall(int index),此 方法返回 rainfall 元素中与给定的 index 对应的值,在 GetRainfall 添加处理任何从 GetRainfall 方法中抛出的越界异常所需要的代码。
2)为读取每月降雨从空中吸收并带到地面的污染物,在类中添加数组 pollution,也 包含 12 个元素,在构造方法中赋任意值;在类中编写另一个方法,头为:public int GetAveragePollution(int index),来计算给定月份单位降雨量中的污染物,例如,计算 4 月 份 单 位 降 雨 量 所 含 污 染 物 用 以 下 计 算 来 实 现 : averagePollution=pollutin[3]/rainfall[3];在此方法中实现处理异常的代码。注意,此 方法既可以抛出索引越界异常,也可以抛出被 0 除异常。 3)编写测试代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Meteorologist
{
public int[] rainfall;
public int[] pollution = new int[12];
public double averagePollution;
public Meteorologist()
{
rainfall = new int[] { 16,12,15,14,13,19,25,26,35,16,17,20 };
Console.WriteLine("请输入1-12月的污染物含量(单位:ml)");
for (int i = 0; i < 12; i++)
{
pollution[i] = Convert.ToInt32(Console.ReadLine());
}
}
public int GetRainfall(int index) //返回给定的index对应的值
{
try
{
return rainfall[index];
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("数组下标越界");
return 0;
}
catch (FormatException)
{
Console.WriteLine("数组下标非数字异常");
return 0;
}
}
public int GetAveragePollution(int index)//计算单位降雨量中污染物
{
try
{
averagePollution = pollution[index] / GetRainfall(index);
averagePollution = (double)pollution[index] / (double)GetRainfall(index);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("数组下标越界异常");
}
catch (DivideByZeroException)
{
Console.WriteLine("除数为零异常");
}
Console.WriteLine("{0}月份单位降雨量所含污染物百分比为:{1}%", index, averagePollution * 100);
return 0;
}
}
public class Text
{
public static void Main()
{
int m;
Console.WriteLine("单位降雨量所含污染物百分比计算");
Meteorologist Mt = new Meteorologist();
Console.WriteLine("请输入月份:");
m = Convert.ToInt32(Console.ReadLine());
Mt.GetAveragePollution(m - 1);
}
}
第三部分 Windows 应用程序设计
实验一 文本编辑器的设计
查找:
替换:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace yunnote
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (b == true && rtbNotepad.Modified == true)
{
rtbNotepad.SaveFile(odlgNotepad.FileName, RichTextBoxStreamType.PlainText);
s = true;
}
else if (b == false && rtbNotepad.Text.Trim() != "" && sdlgNotepad.ShowDialog() == DialogResult.OK)
{
rtbNotepad.SaveFile(sdlgNotepad.FileName, RichTextBoxStreamType.PlainText);
s = true;
b = true;
odlgNotepad.FileName = sdlgNotepad.FileName;
}
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (b == true || rtbNotepad.Text.Trim() != "")
{
// 若文件未保存
if (s == false)
{
string result;
result = MessageBox.Show("文件尚未保存,是否保存?", "保存文件", MessageBoxButtons.YesNoCancel).ToString();
switch (result)
{
case "Yes":
// 若文件是从磁盘打开的
if (b == true)
{
// 按文件打开的路径保存文件
rtbNotepad.SaveFile(odlgNotepad.FileName, RichTextBoxStreamType.PlainText);
}
// 若文件不是从磁盘打开的
else if (sdlgNotepad.ShowDialog() == DialogResult.OK)
{
rtbNotepad.SaveFile(sdlgNotepad.FileName, RichTextBoxStreamType.PlainText);
}
s = true;
rtbNotepad.Text = "";
break;
case "No":
b = false;
rtbNotepad.Text = "";
break;
case "Cancel":
b = false;
break;
}
}
else
{
b = false;
rtbNotepad.Text = "";
}
}
}
private void rtbNotepad_TextChanged(object sender, EventArgs e)
{
// 文本被修改后,设置s为false,表示文件未保存
s = false;
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (b == true || rtbNotepad.Text.Trim() != "")
{
if (s == false)
{
string result;
result = MessageBox.Show("文件尚未保存,是否保存?", "保存文件", MessageBoxButtons.YesNo).ToString();
switch (result)
{
case "Yes":
if (b == true)
{
rtbNotepad.SaveFile(odlgNotepad.FileName, RichTextBoxStreamType.PlainText);
}
else if (sdlgNotepad.ShowDialog() == DialogResult.OK)
{
rtbNotepad.SaveFile(odlgNotepad.FileName, RichTextBoxStreamType.PlainText);
}
s = true;
break;
case "No":
b = false;
rtbNotepad.Text = "";
break;
}
}
}
odlgNotepad.RestoreDirectory = true;
if ((odlgNotepad.ShowDialog() == DialogResult.OK) && odlgNotepad.FileName != "")
{
rtbNotepad.LoadFile(odlgNotepad.FileName, RichTextBoxStreamType.PlainText);
b = true;
}
s = true;
}
private void mnuItemSaveAs_Click(object sender, EventArgs e)
{
if (sdlgNotepad.ShowDialog() == DialogResult.OK)
{
rtbNotepad.SaveFile(sdlgNotepad.FileName, RichTextBoxStreamType.PlainText);
s = true;
}
}
private void mnuItemClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.Undo();
}
private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.Copy();
}
private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.Cut();
}
private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.Paste();
}
private void 日期ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.AppendText(DateTime.Now.ToString());
}
private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
{
rtbNotepad.SelectAll();
}
private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mnuItemAuto.Checked == false)
{
mnuItemAuto.Checked = true;
rtbNotepad.WordWrap = true;
}
else
{
mnuItemAuto.Checked = false;
rtbNotepad.WordWrap = false;
}
}
private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
fdlgNotepad.ShowColor = true;
if (fdlgNotepad.ShowDialog() == DialogResult.OK)
{
rtbNotepad.SelectionColor = fdlgNotepad.Color;
rtbNotepad.SelectionFont = fdlgNotepad.Font;
}
}
private void 工具栏ToolStripMenuItem_Click(object sender, EventArgs e)
{
Point point;
if (mnuItemToolStrip.Checked == true)
{
// 隐藏工具栏时,把坐标设为(0,24),因为菜单的高度为24
point = new Point(0, 24);
mnuItemToolStrip.Checked = false;
tslNotepad.Visible = false;
// 设置多格式文本框左上角位置
rtbNotepad.Location = point;
// 隐藏工具栏后,增加文本框高度
rtbNotepad.Height += tslNotepad.Height;
}
else
{
/* 显示工具栏时,多格式文本框左上角位置的位置为(0,49),
因为工具栏的高度为25,加上菜单的高度24后为49 */
point = new Point(0, 49);
mnuItemToolStrip.Checked = true;
tslNotepad.Visible = true;
rtbNotepad.Location = point;
rtbNotepad.Height -= tslNotepad.Height;
}
}
private void 状态栏ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mnuItemStatusStrip.Checked == true)
{
mnuItemStatusStrip.Checked = false;
stsStatusStrip.Visible = false;
rtbNotepad.Height += stsStatusStrip.Height;
}
else
{
mnuItemStatusStrip.Checked = true;
stsStatusStrip.Visible = true;
rtbNotepad.Height -= stsStatusStrip.Height;
}
}
private void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmFind frmFind = new FrmFind(this);
frmFind.Show();
}
private void 替换ToolStripMenuItem_Click(object sender, EventArgs e)
{
form3 change = new form3(this);
change.Show();
}
}
}
查找框:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace yunnote
{
public partial class FrmFind : Form
{
public FrmFind()
{
InitializeComponent();
}
private void btnFind_TextChanged(object sender, EventArgs e)
{
if (txtFind.Text != "")
btnFind.Enabled = true;
else btnFind.Enabled = false;
flag = false;
start = 0;
}
private void btnFind_Click(object sender, EventArgs e)
{
string findText = txtFind.Text;
int index = richtxt.IndexOf(findText, start);
if (index == -1)
{
if (flag)
MessageBox.Show("已经到文件尾");
else
MessageBox.Show(string.Format("查不到{0}", findText));
}
else if (index >= richtxt.Length - 1)
{
MessageBox.Show("已经到文件尾");
}
else
{
flag = true;
richbox.Select(index, findText.Length);
richbox.Focus();
start = index + findText.Length;
}
}
}
}
替换框:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace yunnote
{
public partial class form3 : Form
{
public form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void form3_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string findText = txtFind.Text;
int index = richtxt.IndexOf(findText, start);
if (index == -1)
{
if (flag)
MessageBox.Show("已经到文件尾");
else
MessageBox.Show(string.Format("查不到{0}", findText));
}
else if (index >= richtxt.Length - 1)
{
MessageBox.Show("已经到文件尾");
}
else
{
flag = true;
richbox.Select(index, findText.Length);
richbox.SelectedText = txtReplace.Text;
start = index + findText.Length;
}
}
private void button2_TextChanged(object sender, EventArgs e)
{
if (txtFind.Text != "")
btnFind.Enabled = true;
else btnFind.Enabled = false;
flag = false;
start = 0;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
实验二 ADO.NET 程序设计
登录界面:
通讯录界面:
浏览:
查询:
数据库:
create table telephoneinfo(
PersonID int identity(1,1) ,
Name char(8),
Sex char(2),
OfficeTel int,
HomeTel int,
Mark char(20))
create table userinfo
(
UserID int identity(1,1) ,
UserName char(8),
PassWord int)
主要代码:
通讯录界面:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace yuntongxunlu
{
public partial class 通讯录界面 : Form
{
public 通讯录界面()
{
InitializeComponent();
}
private void 通讯录界面MainForm_Load(object sender, EventArgs e)
{
登录 load = new 登录();
load.ShowDialog();
if ((int)load.Tag == 0)
{
this.Close();
}
}
private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
{
添加通讯录界面 af = new 添加通讯录界面();
af.ShowDialog();
}
private void 浏览ToolStripMenuItem_Click(object sender, EventArgs e)
{
查询信息 vif = new 查询信息();
vif.ShowDialog();
}
private void 用户添加ToolStripMenuItem_Click(object sender, EventArgs e)
{
添加用户界面 auf = new 添加用户界面();
auf.ShowDialog();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void 通讯录界面_Load(object sender, EventArgs e)
{
登录 load = new 登录();
load.ShowDialog();
if ((int)load.Tag == 0)
{
this.Close();
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = System.DateTime.Now.ToString();
}
}
}
登录界面:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace yuntongxunlu
{
public partial class 登录 : Form
{
public 登录()
{
InitializeComponent();
}
SqlClass sql1 = new SqlClass();
private void button1_Click(object sender, EventArgs e)
{
if (name.Text.Trim() == "" || mima.Text.Trim() == "")
{
MessageBox.Show("请完成填写信息", "提示");
}
else
{
try
{
sql1.conn.Open();
string str = "select *from userinfo where UserName='" + name.Text.ToString() + "'and PassWord='" + mima.Text.ToString() + "'";
SqlCommand comm = new SqlCommand(str, sql1.conn);
Console.WriteLine("nihao hello");
if (comm.ExecuteScalar() != null)
{
sql1.conn.Close();
Tag = 1;
this.Close();
}
else
{
MessageBox.Show("信息有误,请重新登录!", "提示");
sql1.conn.Close();
}
}
catch (SqlException ex)
{
ex.ToString();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
Tag = 0;
this.Close();
}
}
}
查询浏览界面:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace yuntongxunlu
{
public partial class 查询信息 : Form
{
public 查询信息()
{
InitializeComponent();
}
public SqlClass sql = new SqlClass();
public DataSet ds = new DataSet();
private void 查询信息_Load(object sender, EventArgs e)
{
banding();
}
public void banding()
{
sql.conn.Open();
string str = "select telephoneinfo.PersonID as 自动编号,telephoneinfo.Name as 姓名,telephoneinfo.Sex as 性别,telephoneinfo.OfficeTel as 电话,telephoneinfo.HomeTel as 家庭电话,telephoneinfo.Mark as 备注 from telephoneinfo order by PersonID";
SqlDataAdapter da = new SqlDataAdapter(str, sql.conn);
//ds = new DataSet();
da.Fill(ds, "phone");
if (ds.Tables[0].Rows.Count != 0)
info1.DataSource = ds.Tables[0].DefaultView;
else
info1.DataSource = null;
info1.CaptionText = "您目前有 " + ds.Tables[0].Rows.Count + "个人的电话";
sql.conn.Close();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (info1.CurrentCell.RowNumber >= 0 && info1.DataSource != null)
{
sql.conn.Open();
string str = "delete from telephoneinfo where Name='" + ds.Tables["phone"].Rows[info1.CurrentCell.RowNumber][1].ToString() + "'";
SqlCommand comm = new SqlCommand(str, sql.conn);
comm.ExecuteNonQuery();
MessageBox.Show("删除'" + ds.Tables["phone"].Rows[info1.CurrentCell.RowNumber][1] + "'电话成功", "提示");
sql.conn.Close();
banding();
}
else
{
MessageBox.Show("删除失败", "提示");
}
}
private void button1_Click(object sender, EventArgs e)
{
sql.conn.Open();
string str = " select telephoneinfo.PersonID as 自动编号,telephoneinfo.Name as 姓名,telephoneinfo.Sex as 性别,telephoneinfo.OfficeTel as 电话,telephoneinfo.HomeTel as 家庭电话,telephoneinfo.Mark as 备注 from telephoneinfo where Name='" + textBox1.Text.Trim() + "'";
SqlDataAdapter da = new SqlDataAdapter(str, sql.conn);
ds = new DataSet();
da.Fill(ds, "phone");
if (ds.Tables[0].Rows.Count != 0)
info1.DataSource = ds.Tables[0].DefaultView;
else
{
info1.DataSource = null;
MessageBox.Show("没有此人", "提示");
}
info1.CaptionText = "查找个人结果";
sql.conn.Close();
}
}
}
添加用户界面
namespace yuntongxunlu
{
public partial class 添加用户界面 : Form
{
public 添加用户界面()
{
InitializeComponent();
}
SqlClass sql1 = new SqlClass();
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "" && textBox2.Text.Trim() == "")
{
MessageBox.Show("请填写姓名密码!", "提示");
}
else
{
sql1.conn.Open();
string str = "select*from userinfo where UserName='" + textBox1.Text.ToString() + "'";
SqlCommand comm = new SqlCommand(str, sql1.conn);
if (null != comm.ExecuteScalar())
{
MessageBox.Show("已有此姓名", "提示");
sql1.conn.Close();
}
else
{
string str2 = "insert into[userinfo]([UserName],[PassWord]) values('" + textBox1.Text.Trim() + "','" + textBox2.Text.Trim() + "')";
comm.CommandText = str2;
comm.ExecuteNonQuery();
textBox1.Clear();
textBox2.Clear();
MessageBox.Show("添加成功", "提示");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
修改界面
namespace yuntongxunlu
{
public partial class 修改界面 : Form
{
查询信息 fm;
SqlClass sql;
string str1, str2, str3, str4, str5;
Int32 sss;
public 修改界面(查询信息 f1)
{
fm = f1;
sql = fm.sql;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string s1, s2, s3, s4, s5;
s1 = textBox1.Text;
s2 = comboBox1.Text;
s3 = textBox2.Text;
s4 = textBox4.Text;
s5 = textBox2.Text;
if (str1.Equals(s1) && str2.Equals(s2) && str3.Equals(s3) && str4.Equals(s4) && str5.Equals(s5)) { }
else
{
sql.conn.Open();
string str = "update telephoneinfo set Name='" + s1 + "',Sex='" + s2 + "',OfficeTel='" + s3 + "',HomeTel='" + s4 + "',Mark='" + s5 + "' where PersonID=" + sss;
SqlCommand comm = new SqlCommand(str, sql.conn);
comm.ExecuteNonQuery();
MessageBox.Show("修改成功", "提示");
sql.conn.Close();
fm.banding();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void ChangeForm_Load(object sender, EventArgs e)
{
if (fm.info1.CurrentRowIndex >= 0 && fm.info1.DataSource != null)
{
str1 = fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][1].ToString();
str2 = fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][2].ToString();
str3 = fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][3].ToString();
str4 = fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][4].ToString();
str5 = fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][5].ToString();
sss = Convert.ToInt32(fm.ds.Tables["phone"].Rows[fm.info1.CurrentCell.RowNumber][0]);
textBox1.Text = str1;
textBox2.Text = str3;
textBox4.Text = str4;
textBox2.Text = str5;
comboBox1.Text = str2;
}
}
}
}