2014-09-29 61 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;