首頁  >  文章  >  後端開發  >  C#單位轉換器的圖文程式碼詳細介紹

C#單位轉換器的圖文程式碼詳細介紹

黄舟
黄舟原創
2017-03-08 11:24:502213瀏覽

這篇文章主要為大家詳細介紹了C#單位轉換器簡單案例,一個簡單的winform應用程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下

經過幾天學習,寫出了一個簡單的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 < &#39;0&#39;) || (e.KeyChar > &#39;9&#39;))//允许输入0-9数字 
    {
     e.Handled = true;
    }
   } 
  }


#

以上是C#單位轉換器的圖文程式碼詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn