2014-09-29 60 views
0

我想用一个字符串值 这样如何通过字符串访问Control变量?

Random rnd = new Random(); 
int x= rnd.Next(1, 10); 
string ime = "pictureBox" + x.ToString(); 
ime.BackColor = Color.CornflowerBlue; 

但是,这并不工作

+2

当然不是..'string'不是'PictureBox' ..因此,一个'BackColor'属性不存在。 – 2014-09-29 05:34:04

+0

不,你不需要通过string_访问一个变量。 **你需要一个数组**。 – Krumia 2014-09-29 05:35:43

+0

http://stackoverflow.com/questions/18434263/c-sharp-use-a-string-to-call-a-variable,http://stackoverflow.com/questions/20857773/create-dynamic-variable-name ,http://stackoverflow.com/questions/23699542/how-can-i-access-to-all-comboboxes-by-for-loop-in-c,http://stackoverflow.com/questions/4483912/find -a - 控制 - 在-C-尖锐的WinForms按姓名 – user2864740 2014-09-29 05:40:55

回答

1

下面的代码应该为你工作,

Random rnd = new Random(); 
int x= rnd.Next(1, 10); 
string ime = "pictureBox" + x.ToString(); 
((PictureBox)frm.Controls.Find(ime ,true)[0]).BackColor = Color.CornflowerBlue; 
2

你不是真的想用这样的字符串。你想用这个名字得到一个控件并像这样使用它。您可以通过名字来取得控制类似如下:

var pictureBox = myForm.Controls[ime]; 
0

代替生成一个随机命名,并使用它来做找到该名称的图片框的,直接挑一个随机的图片框:

Random rnd = new Random(); 
var pictureBoxes = frm.Controls.OfType<PictureBox>().ToArray(); 
var randomPictureBox = pictureBoxes[rnd.Next(pictureBoxes.Length)]; 

randomPictureBox.BackColor = Color.CornflowerBlue;