C#单位转换器的图文代码详细介绍


本文摘自PHP中文网,作者黄舟,侵删。

这篇文章主要为大家详细介绍了C#单位转换器简单案例,一个简单的winform应用程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

经过几天学习,写出了一个简单的winform应用程序,贴出源码,以备不时之需。

软件启动后的界面如下图所示:

如图,该程序由6个label、8个comboBox、8个textBox和4个button组成。右边4个textBox设置ReadOnly属性为true。

软件启动时,可以让comboBox显示默认项,需要用到comboBox.SelectedIndex语句,默认情况下,comboBox.SelectedIndex="-1"(即默认不显示任何项),将-1改为0即可显示第一项。将代码放到窗体的Load事件里。代码实例:

1

2

3

4

5

6

7

8

9

10

11

private void MainForm_Load(object sender, EventArgs e)

  {

   comboBox1.SelectedIndex = 0;

   comboBox2.SelectedIndex = 1;

   comboBox3.SelectedIndex = 0;

   comboBox4.SelectedIndex = 1;

   comboBox5.SelectedIndex = 0;

   comboBox6.SelectedIndex = 1;

   comboBox7.SelectedIndex = 0;

   comboBox8.SelectedIndex = 1;

  }

按下确定按钮,执行转换函数,计算结果转换为string类型,并将其赋值给textBox.Text,代码实例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

private void button4_Click(object sender, EventArgs e)

{

 string str1, str2;

 str1=Convert.ToString(comboBox7.SelectedItem);

 str2=Convert.ToString(comboBox8.SelectedItem);

 double d1, d2;

 if (textBox7.Text == "")

 {

  textBox7.Text = "1";

  d1 = 1;

 }

 else

  d1 = Convert.ToDouble(textBox7.Text);

 if (str1 == str2)

 {

  d2 = d1;

  textBox8.Text = Convert.ToString(d2);

 }

 else

 {

  if(str1 == "摄氏度" && str2 == "华氏度")

  {

   d2=1.8*d1+32;

   textBox8.Text = Convert.ToString(d2);

  }

  if(str1 == "摄氏度" && str2 == "开氏度")

  {

   d2=d1+273.15;

   textBox8.Text = Convert.ToString(d2);

  }

  if(str1 == "华氏度" && str2 == "摄氏度")

  {

   d2=(d1-32)/1.8;

   textBox8.Text = Convert.ToString(d2);

  }

  if(str1 == "华氏度" && str2 == "开氏度")

  {

   d2=(d1-32)/1.8+273.15;

   textBox8.Text = Convert.ToString(d2);

  }

  if (str1 == "开氏度" && str2 == "摄氏度")

  {

   d2 = d1 - 273.15;

   textBox8.Text = Convert.ToString(d2);

  }

  if (str1 == "开氏度" && str2 == "华氏度")

  {

   d2 = (d1 - 273.15) * 1.8 + 32;

   textBox8.Text = Convert.ToString(d2);

  }

 }

}

使输入框禁止输入除退格键、数字键和小数点键之外的按键(温度的转换可以输入负号),防止用户输入非数字字符使程序发生错误。在keypress事件中添加相关代码,代码实例:

1

2

3

4

5

6

7

8

9

10

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

{

 if (e.KeyChar != '\b' && e.KeyChar != 46)//允许输入退格键和小数点键

 {

  if ((e.KeyChar < '0') || (e.KeyChar > '9'))//允许输入0-9数字

  {

   e.Handled = true;

  }

 }

}

以上就是C#单位转换器的图文代码详细介绍的详细内容!

相关阅读 >>

C#基于正则表达式抓取a标签链接和innerhtml的方法

详解C#集合类型大盘点的图文代码

C#中序列化实现深拷贝和datagridview初始化刷新的方法介绍

什么是C#中的多态性?

详细介绍用C#描述数据结构2:array的图文代码实例

教你用C#检测含有中文字符串的实际长度

C#日期格式转换的公共方法类的实现详解

C#开发实例-订制屏幕截图工具(二)创建项目、注册热键、显示截图主窗口

C#创建excel文件并将数据导出到excel文件的示例代码详解(图)

详解C#创建dll类库的方法分享(图文)

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...