The Codesee
The Codesee

Reputation: 3783

Use variable as part of resource name

I have a Picturebox named pictureBoxLoadingMsg and am trying to set it's background image inside a timer. Each time the timer ticks, I want to change the image of the picturebox.

I am trying to use a variable as part of the resource name. Examples of the image file names are loading1 and loading2.

I want to use the variable i (which will be an incrementing integer e.g 1, 2, 3) as part of the resource name. I have tried concatenating it to 'loading' (the first part of the resource name), but the code has errors and will not run - it says:

Resources does not contain a definition for loading

int i = 0;
private void TimerLoadingMessages_Tick(object sender, EventArgs e)
{
   pictureBoxLoadingMsg.Image = Properties.Resources.loading + i; 
   // should result in loading1 on the first tick, loading2 on the second tick and so on
   i++;
}

Upvotes: 1

Views: 479

Answers (2)

Fildor
Fildor

Reputation: 16104

You need to compose your key, then lookup the value:

pictureBoxLoadingMsg.Image = (Image)Properties.Resources.ResourceManager.GetObject($"loading{i}"]);

where i is the running index and "loading" whatever the fix part of the key is. GetObject will return an object, so you need to cast to the actual type.

Please also read and consider the remarks given in the docs: ResourceManager.GetObject(string)

Upvotes: 2

Mais1
Mais1

Reputation: 1

There is too less info!

  • what type is pictureBoxLoadingMsg?
  • The error says that the problem is on resources, Resources are done right?

Try some:

pictureBoxLoadingMsg.Image = string.Format({0}{1}, Properties.Resources.loading, i);

Upvotes: 0

Related Questions