2015-12-11 23 views
0

我的問題:Id喜歡,在選擇兩個combobox變量後,將這兩個分開,並將Textbox設置爲計算結果。用兩個選定的組合框項目計算textbox.text

兩個Comboboxes:Körpergröße& Gewicht

textbox:BMI

首先,使用代碼IM(這顯然心不是現在的工作)

 protected void Körpergröße_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     int a; 
     int b; 
     //In this way you can compare the value and if it is possible to convert into an integer. 
     if (int.TryParse(Körpergröße.SelectedItem.ToString(), out a) && int.TryParse(Gewicht.SelectedItem.ToString(), out b)) 
     { 

      fillTextBox(a, b); 
     } 
    } 

    protected void Gewicht_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     int a; 
     int b; 
     if (int.TryParse(Körpergröße.SelectedItem.ToString(), out a) && int.TryParse(Gewicht.SelectedItem.ToString(), out b)) 
     { 

      fillTextBox(a, b); 
     } 
    } 

    private void fillTextBox(int value1, int value2) 
    { 
     BMI.Text = (value1/value2).ToString(); 
    } 

的兩個comboboxes的默認值是字符串..(「Bitte ausw爲hLen「)

圖片怎麼它看起來像現在。選擇兩個int值後,計算結果應顯示在BMI Textbox中。

Picture

這將是很好,如果有人可以回答我用一些圖片的標題說明一個代碼,爲了讓我明白了..提前

謝謝!

回答

-1

整數值不能被餘數分開。所以,你需要改變int類型float類型:

private void Gewicht_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    float a; 
    float b; 
    if (float.TryParse(Körpergröße.SelectedItem.ToString(), out a) && float.TryParse 
(Gewicht.SelectedItem.ToString(), out b)) 
    { 
     fillTextBox(a, b); 
     string str = ""; 
    } 
} 

如果計算兩個整數,例如:

int k=130/150; 

在現實生活中,我們知道,k0.86。但是沒有機會顯示類型integer的剩餘部分,因爲這種類型是不可分割的。 int類型的值不能爲0,58.8。它可以只是1,5或任何整數類型。

float類型可以存儲(有)值,如100,5233.333。這就是爲什麼你看到0而不是你的價值的原因。

如果你想整型值後,以限制人數的數量,你可以使用.ToString()方法的重載:

private void fillTextBox(float value1, float value2) 
{ 
    textBox.Text = ((value1/value2)).ToString("0.00");    
} 

更多細節

Custom Numeric Format Strings on MSDN
+0

@Sasa隨意問任何問題!:) – StepUp

+0

@Sasa如果我的回答可以幫助解決你的問題,你可以將它作爲一個答案,以簡化未來搜索其他人。 – StepUp

-1

我會建議使用SelectionChanged事件並附加該到你的組合框,從兩個獲得選定的值,然後確保你沒有任何null值(string可以爲空,但int不能)更類似於這樣的東西:

XAML

<ComboBox Name="cb1" SelectionChanged="GetText" SelectionMode="Single"> 
    <ComboBoxItem>1</ComboBoxItem> 
    <ComboBoxItem>2</ComboBoxItem> 
    <ComboBoxItem>3</ComboBoxItem> 
</ComboBox> 

<ComboBox Name="cb2" SelectionChanged="GetText" SelectionMode="Single"> 
    <ComboBoxItem>1</ComboBoxItem> 
    <ComboBoxItem>2</ComboBoxItem> 
    <ComboBoxItem>3</ComboBoxItem> 
</ComboBox> 

C#

void GetText(object sender, SelectionChangedEventArgs args) 
{ 
    ComboBoxItem item1 = cb1.SelectedItem as ComboBoxItem); 
    ComboBoxItem item2 = cb2.SelectedItem as ComboBoxItem); 

    if(item1 == null || item2 == null) 
     return; 
    //convert to # with your tryParse 
    fillTextBox(item1, item2); 
} 
相關問題