我想用一個字符串值 這樣如何通過字符串訪問Control變量?
Random rnd = new Random();
int x= rnd.Next(1, 10);
string ime = "pictureBox" + x.ToString();
ime.BackColor = Color.CornflowerBlue;
但是,這並不工作
我想用一個字符串值 這樣如何通過字符串訪問Control變量?
Random rnd = new Random();
int x= rnd.Next(1, 10);
string ime = "pictureBox" + x.ToString();
ime.BackColor = Color.CornflowerBlue;
但是,這並不工作
下面的代碼應該爲你工作,
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;
你不是真的想用這樣的字符串。你想用這個名字得到一個控件並像這樣使用它。您可以通過名字來取得控制類似如下:
var pictureBox = myForm.Controls[ime];
代替生成一個隨機命名,並使用它來做找到該名稱的圖片框的,直接挑一個隨機的圖片框:
Random rnd = new Random();
var pictureBoxes = frm.Controls.OfType<PictureBox>().ToArray();
var randomPictureBox = pictureBoxes[rnd.Next(pictureBoxes.Length)];
randomPictureBox.BackColor = Color.CornflowerBlue;
當然不是..'string'不是'PictureBox' ..因此,一個'BackColor'屬性不存在。 – 2014-09-29 05:34:04
不,你不需要通過string_訪問一個變量。 **你需要一個數組**。 – Krumia 2014-09-29 05:35:43
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