Dynamically create controls in a service

  • Thread starter Thread starter Sean
  • Start date Start date
S

Sean

Hello all,

I may just not be searching for the right thing, but I've been looking for a
way to dynamically create controls (and name them) in my code so that I can
create only the controls I need at run time. For example, I'm writing a
filewatcher service that will eventually write back to a database, but I may
need the service to watch multiple directories (thus, multiple
FileSystemWatcher components). The rub is this...how do I create these
dynamically. Here's what I've tried, and obviously had no luck.

code snippet------------------------------------------

string SQL = "SELECT something from Something else where X=1 and Y=2";

SqlCommand cmd = new SqlCommand(SQL, Conn1);
SqlDatareader dr = cmd.ExecuteReader();

if(dr.hasrows)
{
int x = 0;
while(dr.read())
{
//This is where I need to create a dynamic FileSystemWatcher
component.
FileSystemWatcher fw(x) = new FileSystemWatcher(); //obviously, this
doesn't work but hopefully you can see what I'm aiming for.
fw(x).Path = @"C:\Somepath"; //this will actually be pulled from the
datareader (dr).
fw(x).Filter = "*.*";
fw(x).IncludeSubdirectories = true;
fw(x).Changed += new System.IO.FileSystemEventHandler(OnChanged);
}
}

I know the above is not complete, but I'm hoping that someone gets the idea
of what I'm trying to do. There could be multiple paths that need to be
watched and I will not know that until runtime. I'll be pulling the info
from a database.

Thanks for your help!
 
Sean,

Your FileSystemWatcher instances will just be objects, not controls, and
there's no need to name them. However, you do need to keep them in some
higher-level scope if you want them to be available after their population.
A collection object that is a field in your service class is a reasonable
candidate for this. e.g.:

private ArrayList watchers = new ArrayList();
//...
private void AddWatcher(string path, string filter, bool
includeSubdirectories)
{
FileSystemWatcher newWatcher = new FileSystemWatcher(path, filter);
newWatcher.IncludeSubdirectories = includeSubdirectories;
newWatcher.Changed += new FileSystemEventHandler(OnChanged);

this.watchers.Add(newWatcher);
}

With this setup, you can run through your datareader, calling AddWatcher for
each row with parameter values read from the datareader.

HTH,
Nicole
 
Nicole, I figured it was going to be something very simple. I had the old
"Forest through the trees" syndrome.

Thanks again!

Sean
 
Back
Top