2016-08-22 8 views
-2

私のコードでは、2つのbutton_Clickメソッドを使用しています。私は他のメソッドの最初のメソッドからいくつかの変数の値を使用したい。例:hbutton1_Clickで定義されているwの値をbutton2_Clickに使用します。出来ますか?あなたのbutton1_Clickあなたはクラスのhwに、ローカル変数に代入されていないでC#のあるメソッドから別のメソッドへの変数値の使い方は?

public int h, w; 
public Form1() 
{ 
    InitializeComponent(); 

    textBox1.Text = "Image Path here ..."; 
} 

public void button1_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog dlg = new OpenFileDialog(); 
    dlg.Title = "Select an Image"; 
    dlg.Filter = "jpg files (*.jpg)|*.jpg"; 
    if (DialogResult.OK == dlg.ShowDialog()) 
    { 
     this.pictureBox1.Image = new Bitmap(dlg.FileName); 
     Bitmap img = new Bitmap(dlg.FileName); 
     int w = img.Width; 
     int h = img.Height; 
     pictureBox1.Height = h; 
     pictureBox1.Width = w; 
     textBox1.Text = dlg.FileName; 
    } 
} 

public void button2_Click(object sender, EventArgs e) 
{ 
    MessageBox.Show("Height is- " + h.ToString() + " Width is- " + w.ToString(), "Height & Width"); 
} 
+0

メンテナンス可能なコード(例: 'textbox1'はあまり記述的ではない)を書くことを学ぶべきです。' Bitmap'を2回作成するような無駄なコードを削除してください。また、 'String.Format'を使用してテキストの書式を設定する必要があります。そして、テキストを正しくインデントします。メッセージボックスのタイトルとアイコンを設定する必要があります。 – Phil1970

答えて

1

。ただ、

w = img.Width; 
h = img.Height; 

int w = img.Width; 
int h = img.Height; 

を変更し、私はあなたが達成しようとしているものを正しく理解すれば、それは、動作するはずです。

関連する問題