2013年9月21日 星期六

C# 單位換算器

簡單的來說就是單位換算,因為Combobox的值需要因為Button切換而改變,故採用以下寫法。
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
        test.Add("1", "dfdfdf");
        test.Add("2", "dfdfdf");
        test.Add("3", "dfdfdf");
        comboBox1.DataSource = new BindingSource(test, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key";

// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;

Debug過程:
1.float num_ori= Convert.ToDouble(txt.Text),無法一開始宣告,因為txt.Text一開始不存在,所以不宣告而採用在後面判斷時直接轉換。
2.Combobox的取值時機,在SelectedIndexChanged事件下,當選取長度、質量、容積,任一button時,SelectedIndex跟SelectedText的值就會觸發而帶入,所得到的值為0,以至於後續無法轉換;Click事件下,則是選取Combobox時,造成值的觸發,結果帶入一樣為0;SelectionChangeCommitted事件下,則是當確定選取完成時,SelectedIndex跟SelectedText的值才會帶入,故後面判斷才能進行。

用cmd執行 cd  Documents\Visual Studio 2010\Projects\unitconversion\unitconversion 到檔案所在的資料夾底下,再輸入 csc Form1.cs  Form1.Designer.cs Program.cs  ,最後打上 Program.exe執行。

以下附上一張執行成果


檔案連結:

參考資料:

ComboBox: Adding Text and Value to an Item



沒有留言:

張貼留言