[Solved] Sharing c# variables between methods? [closed]


There are a couple of options. Since these methods are event handlers and aren’t directly invoked, the best approach here is likely to make the variable class-level members:

private string strHeaderFileName;

protected void multiFileUpload_FileUploaded(object sender, FileUploadedEventArgs e)
{
    strHeaderFileName = e.File.FileName;
    // etc.
}

protected void btnSave_Click(object sender, EventArgs e)
{
    // here you can access strHeaderFileName
}

As class-level members, they will be accessible by any method in that class. (Make sure you keep them private or other objects will be able to access them too, which you probably don’t want in this case.) And they will exist for the lifetime of any given instance of that class.

Also note that this looks like ASP.NET, which behaves a little differently in terms of class instances than things like WinForms. Any given instance of a Page doesn’t persist between requests. So if you set the value in one handler, display the page again, and then invoke another handler the value won’t be there anymore. This is because the class instance for each Page is created per-request and then destroyed after the response.

To persist across page requests, you’d need to keep the value somewhere else. For example, if it needs to live during the scope of that user’s session then you can put it in session state:

protected void multiFileUpload_FileUploaded(object sender, FileUploadedEventArgs e)
{
    Session["strHeaderFileName"] = e.File.FileName;
    // etc.
}

protected void btnSave_Click(object sender, EventArgs e)
{
    // here you can access Session["strHeaderFileName"]
}

Depending on the scope in which the value needs to persist, you could also put it on the page, in a cookie, in a database, some caching mechanism, etc.

solved Sharing c# variables between methods? [closed]