Search code examples
c#excelformsvariablesreturn

how to return this variable from a button to be use for all the form


I'm trying to use a openfileDialog to insert a file from a button and then return the file name tu be use to read the file in another form

private void buttin1_Click(object sender, EventArgs e)
{
OpenFileDialog File = new OpenFileDialog();
var FileName = File.FileName;
return FileName; 
}

private void buttin2_Click(object sender, EventArgs e)
{
DataTable dtexcel = ReadExcel(FileName);
}




Solution

  • you cannot return anything from your function Button1_Click, better set a variable that will be used by your MainWindow

    public class MainWindow : Window
    {
        private string yourFileName{get;set;}
        //...
        private void buttin1_Click(object sender, EventArgs e)
        {
            OpenFileDialog File = new OpenFileDialog();
            this.yourFileName = File.FileName;
        }
        
        private void buttin2_Click(object sender, EventArgs e)
        {
             if(yourFileName!="" && File.Exists(yourFileName)
             {
                 DataTable dtexcel = ReadExcel(yourFileName);
             }
        }
    }