Web user control member variable not accessible when not declared static
-
12-12-2019 - |
Question
I am creating a web user control using C# to play some .wav files in the server. Following is my code.
public partial class WaveFilePlayer : System.Web.UI.UserControl
{
//private string[] files;
private static string[] files;
protected void ButtonLoad_Click(object sender, EventArgs e)
{
string resourcePath = ConfigurationManager.AppSettings["ResourcePath"];
string searchPattern = ConfigurationManager.AppSettings["SearchPattern"];
files = System.IO.Directory.GetFiles(path, searchPattern);
}
protected void ButtonPlay_Click(object sender, EventArgs e)
{
int selectedIndex = ListBoxFiles.SelectedIndex;
SoundPlayer soundPlayer = new SoundPlayer(files[selectedIndex]);
soundPlayer.Play();
}
As seen in the code above I declare string[] files
as a member variable. Then I assign it in the ButtonLoad_Click
method. But it throws a NullReferenceException
when I try to access it in the ButtonPlay_Click
method unless string[] files
is declared static.
Does it mean that a new object of System.Web.UI.UserControl
is not created while loading the user control in a asp.net page? And does it mean that when multiple clients (browsers) try to play the .wav files, only one instance of the string[] files
is created at the server to be used by all clients?
Solution
I suspect the problem isn't that it can't be accessed, at all. I strongly suspect that the problem is that you've got two different requests, and therefore two different instances of WaveFilePlayer
- so when you're executing ButtonPlay_Click
, the files
variable will be null unless you've written some code to persist it between requests.
Options here would be view state or some server-side session. You should not use a static variable, as that will basically mean you've got a single variable shared between all requests (for all users).