如何在C#中从一个方法访问变量的值到另一个方法? [英] How can I access value of a variable from one method to another method in C# ?
本文介绍了如何在C#中从一个方法访问变量的值到另一个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个GUI功能代码,其中我有两个方法(对于button1和button2)。
我想从button1方法到button2方法访问'h'和'w'变量值。
I have an GUI functioning code, in which I have two methods (for button1 and button2).
I want to access 'h' and 'w' variable values from button1 method to button2 method.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace First
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private 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);
// pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
Bitmap img = new Bitmap(dlg.FileName);
int w = img.Width;
int h = img.Height;
pictureBox1.Height = h;
pictureBox1.Width = w;
textBox1.Text = dlg.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Height is- "+ h.ToString() +"
Width is- " + w.ToString(),"Height & Width");
}
}
}
这只不过是全球化变量。但我无法做到这一点。请在这方面帮助我。
提前谢谢。
我有什么试过:
我试过通过'public int h,w;'方式在程序启动时声明变量。
That is nothing but globalizing the variables. But I am unable to do that.Please help me in this context.
Thank you in advance.
What I have tried:
I have tried by declaring variables in starting of program in 'public int h,w;' way.
推荐答案
是的,您可以使用this.pictureBox1
对象,因为您要将h和w的值分配给button1中的图片框点击事件。
Yes you can, usingthis.pictureBox1
object, since you are assigning the values of h and w to the picture box in the button1 click event.
private void button2_Click(object sender, EventArgs e)
{
int h = pictureBox1.Height;
int w = pictureBox1.Width;
MessageBox.Show("Height is- " + h + " Width is- " + w, "Height & Width");
}
这篇关于如何在C#中从一个方法访问变量的值到另一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文