当前位置: 移动技术网 > IT编程>开发语言>c# > C#单位转换器简单案例

C#单位转换器简单案例

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

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

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

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

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,代码实例:

  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事件中添加相关代码,代码实例:

  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;
    }
   } 
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网