![](/img/trans.png)
[英]How can I change multiple .text values to “”, through calling a method?
[英]How can I change myLable1.Text by calling it as a variable
首先,我說我只是在學習C#,這是我的序言。 除了基本的JavaScript之外,我沒有其他編程經驗,因此我仍然不確定很多正確的術語。 關於這個問題...
假設我有10個標簽; myLabel1,myLabel2,myLabel3等,我有一個名為i的變量。
那么,如何通過切換變量i的結束號來更改myLabel的.Text? 我嘗試制作一個新的字符串:
string labelNumber = "myLable" + Convert.ToString(i);
接着:
lableNumber.Text = "some text";
顯然,這是行不通的,因為.text不是lableNumber的已知方法。
與大多數其他編譯語言一樣,C#不能像許多腳本語言一樣讓您輕松地做到這一點。
如果要通過字符串訪問控件,則需要將它們收集在Dictionay<string, Control>
或者,如果僅關心Labels
,則需要將其收集在Dictionay<string, Label>
:
Dictionary<string, Label> labels = new Dictionary<string, Label>();
// you can do this in a loop over i:
Label newLabel = new Label();
newLabel.Name = "myLabel" + Convert.ToString(i);
// maybe set more properties..
labels.Add(newLabel.Name, newLabel ); // <-- here you need the real Label, though!
flowLayoutPanel1.Controls.Add(newLabel ) // <-- or wherever you want to put them
現在,您可以按名稱訪問每個字符串:
labels["myLabel3"].Text = "hi there";
請注意,將它們添加到Dictionary
中(或者,如果您願意通過索引訪問它們,則添加到List<T>
),在循環創建它們時需要這樣做,因為以后將無法訪問它們。 至少不是沒有反思 ,這對於這種情況來說太過猛了。
還請注意 ,變量名不是字符串,而是編譯器的標記,而變量名是 Name
屬性 ,后者是字符串,但並不意味着要標識變量,因為它不必唯一 ,可以隨時更改 。
我認為您正在嘗試執行以下操作:
// Create N label xontrols
Labels[] labels = new Labels[n];
for (int i = 0; i < n; i++)
{
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// ...
labels[2] .Text = "some text";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.