我是C#中的新手,現在我遇到了一個我無法解決的問題。無法獲取label.text c#
我已經創建了多個的TabPages相同的標籤:
public Label ChosenType = new Label();
private void EvalType()
{
Label labelChosenType = new Label();
labelChosenType.AutoSize = false;
labelChosenType.Left = 710;
labelChosenType.Top = 3;
labelChosenType.Width = 350;
labelChosenType.Height = 96;
labelChosenType.Text = "Some text";
labelChosenType.Font = new Font("Arial", 14, FontStyle.Bold);
labelChosenType.TextAlign = ContentAlignment.MiddleCenter;
labelChosenType.BackColor = Color.Red;
labelChosenType.ForeColor = Color.White;
labelChosenType.Click += new EventHandler(labelChosenType_Click);
tabControl1.SelectedTab.Controls.Add(labelChosenType);
}
private void SetGeneralInfo()
{
for (int i = 0; i < tabControl1.TabCount; i++)
{
tabControl1.SelectTab(i);
EvalType();
}
}
private void labelChosenType_Click(object sender, EventArgs e)
{
MessageBox.Show(labelChosenType.Text);
}
的問題是,消息框爲空。爲什麼我無法從標籤中獲得文字? (這不是主要功能,但這是最簡單的方法,以顯示問題)
我試圖添加名稱= =「一些文本」+我,但它是所有標籤上的相同,它didn沒有工作。
謝謝!
出現的消息框,但它是空白 – donmichael
好像標籤對象的實例僅限於虛空方法,你需要把它'outside'虛空方法 – TheQuestioner
在'labelChoosenType_Click()'方法,「labelChoosenType」標識符指的是什麼?它肯定不會引用'EvalType()'方法中聲明的** local **變量'labelChoosenType'。你有沒有把它設置爲有用的東西?請提供可靠地再現問題的良好[mcve]。哦,這個詞拼寫爲「選擇」。 –