如何从Windows窗体应用程序中的button_Click事件访问变量?

时间:2018-07-05 22:46:14

标签: c# asp.net winforms

我目前正在Windows窗体应用程序上工作,我必须将图像存储到本地目录中并将图像存储到SqlServer数据库中。在主窗体上,我使用了浏览图像按钮,单击该按钮可显示文件对话框。图像名称和路径都存储在两个单独的字符串中,我必须从另一种方法访问该字符串,该方法实际上将标题和图像路径以及其他一些数据存储到数据库中。

我在浏览图像按钮上使用了以下代码。

private void btnBrowseImage_Click(object sender, EventArgs e)
    {
        string saveDirectory = @"D:\ProductImages\";

        OpenFileDialog fileDialog = new OpenFileDialog();
        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            if(!Directory.Exists(saveDirectory))
            {
                Directory.CreateDirectory(saveDirectory);
            }

            string fileName = Path.GetFileName(fileDialog.FileName);
            string fileSavePath = Path.Combine(saveDirectory, fileName);
            File.Copy(fileDialog.FileName, fileSavePath, true);

            string imgTitle = Path.GetFileName(fileName);
            string imgPath = fileSavePath;
        }
    }

现在,我想通过“添加到数据库”按钮访问分别保存文件名和文件路径的两个变量。我将这两个变量以及productName,unitPrice和quantity一起传递给我的Products调用中的AddProduct方法,在那里,它们实际上将被添加到数据库中,如btnAddToDatabase_Click事件所示。

private void btnAddToDatabase_Click(object sender, EventArgs e)
    {

        string productName, unitPrice, quantity, image, imageTitle;

        productName = txtProductName.Text.Trim();
        unitPrice = txtUnitPrice.Text.Trim();
        quantity = txtQuantity.Text.Trim();
        image = 
        imageTitle = 

        Products.AddProduct(productName, quantity, unitPrice);
        FillGrid();
        btnClearFields_Click(sender, e);

    }

我已经尝试了很多,但是没有运气,因为无法从浏览按钮事件中直接访问这些变量,因此我可以将它们定位在所需的位置。有什么办法可以帮助我而不会失败吗?

1 个答案:

答案 0 :(得分:1)

您需要在类中声明变量,而不是在特定方法中声明变量,否则它们将具有类级别的作用域

public class YourClass
{
    private string fileName 
    private string filePath

    private void btnBrowseImage_Click(object sender, EventArgs e)
    {
        // code here
        fileName = Path.GetFileName(fileDialog.FileName);
        filePath= Path.Combine(saveDirectory, fileName);
    }

    private void btnAddToDatabase_Click(object sender, EventArgs e)
    {
        // code here
        fileName = "something";
        filePath="something";
    }
    // other methods
}