c#简单案例--单位转换器
经过几天学习,写出了一个简单的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,代码实例:
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; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架