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

Time:11-22

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);
}



CodePudding user response:

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);
         }
    }
}
  • Related