经由几天进修,写出了一个简朴的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; } } }
以上就是C#单元转换器的图文代码细致引见的细致内容,更多请关注ki4网别的相干文章!