2015-05-04 41 views
-1

我正在制定一個計算能源使用量的程序。我創建了一個單維整數數組,用於存儲程序中每個設備的額定功率。當用戶點擊複選框時,我想獲取數組的第一個元素並在計算中使用它。
複選框方法需要什麼代碼?
另外,如何將int的值轉換爲string,以便我可以將它們打印在文本框中?從數組中使用int值 - c#

public Form1() 
{ 
    InitializeComponent(); 

    int[] AppliancePower = new int[3]; 
    AppliancePower[0] = 5000; 
    AppliancePower[1] = 4000; 
    AppliancePower[2] = 7000; 
} 

private void checkBox1_CheckedChanged(object sender, EventArgs e) 
{ 
} 

回答

3

什麼

public class Form1 
{ 
    private int[] AppliancePower = new[] 
    { 
     5000, 
     4000, 
     7000 
    }; 

    private void checkBox1_CheckedChanged(object sender, EventArgs e) 
    { 
     if (checkBox1.Checked) 
     { 
      var value = AppliancePower[0]; 
      DoSomeFanyCalculation(value); 
      this.textBox1.Text = value.ToString(); 
     } 
     else 
     { 
      this.textBox1.Text = String.Empty; 
     } 
    } 

} 
+1

我得到的錯誤 –

+0

設置你的陣列作爲類,而不是一個局部變量在構造函數中的字段「‘AppliancePower’的名稱在當前環境中不存在」 :) –

+0

在您的示例中,您在構造函數中創建了一個局部變量,並且從不分配它。使其成爲Form1中的全局變量(我更新了我的答案) –

0

是不是很容易。

public class Form1 
{ 
    public int[] AppliancePower; 
    public Form1() 
    { 
     InitializeComponent(); 

     AppliancePower = new int[3]; 
     AppliancePower[0] = 5000; 
     AppliancePower[1] = 4000; 
     AppliancePower[2] = 7000; 
    } 

    private void checkBox1_CheckedChanged(object sender, EventArgs e) 
    { 
     if(AppliancePower.Length > 0) 
     { 
      int FirstValue = AppliancePower[0]; 
      string StringValue = FirstValue .ToString(); 
     } 
    } 
} 
+1

我收到錯誤「名稱'AppliancePower'在當前上下文中不存在」 –

+0

@MichaelRoberts您需要將其聲明爲公共 –

+1

如何? (對此不熟悉) –

0

你可以做其他的2回答表明了什麼,或者你可以節省一步,只是這樣做:

this.textBox1.Text = (checkBox1.Checked) ? AppliancePower[0].ToString() : string.Empty ; 

此外,您還需要聲明AppliancePower上的一流水平,而不是在構造函數:

// class level: 
int[] AppliancePower; 

public Form1() 
{ 
InitializeComponent(); 

AppliancePower = new int[3]; 
AppliancePower[0] = 5000; 
AppliancePower[1] = 4000; 
AppliancePower[2] = 7000; 
} 

private void checkBox1_CheckedChanged(object sender, EventArgs e) 
{ 
    this.textBox1.Text = (checkBox1.Checked) ? AppliancePower[0].ToString() : string.Empty ; 

} 
+1

我收到錯誤「名稱'AppliancePower'在當前上下文中不存在」。我需要在代碼中的某處聲明'AppliancePower'嗎? –