所以,我對編程有點新,並且正如標題所述,嘗試爲面板添加標籤,這兩個標籤都是在運行時通過按鈕點擊創建的在C#中。也許文本框更好,但它不應該做這樣的區別。我已經找到了一些有用的答案,但總的來說,面板在運行之前就已經創建好了。c#在運行時在面板上添加一個標籤
所以,我的問題是:當我編寫代碼時,如何在沒有創建面板的情況下如何將標籤添加到面板上,並使用 newLabel.Parent = panel_name;
。那麼是否可以在面板上添加更多標籤或itembox?
這裏是我的完整代碼按鈕點擊:
// for dragging the panels during runtime
Point move;
Label[] labels = new Label[1000];
Panel[] panels = new Panel[1000];
// To Remove the last created panel
List<Panel> panelsAdded = new List<Panel>();
// increments by one for each created label
int counter = 0;
// sets the posstion in the window for each created panel
int counterpos_x = 50;
int counterpos_y = 50;
// converted string from the combobox where I want to get the text for the label
string str_installation;
// my try... doesn't work
string panel_name;
private void btnCreate_Click(object sender, EventArgs e)
{
if(counter < 40)
{
Panel myPanel = new Panel();
myPanel.Tag = "Panel" + counter;
myPanel.Location = new Point(counterpos_x,counterpos_y)
myPanel.Height = 150;
myPanel.Width = 200;
myPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
panel_name = "Panelnumber" + counter;
// how do I need to declare this for the label to inherit with newLabel.Parent = panel_name
myPanel.Name = panel_name;
// for dragging the panel
myPanel.MouseMove += new MouseEventHandler(myPanel_MouseMove);
myPanel.MouseDown += new MouseEventHandler(myPanel_MouseDown);
panels[counter] = myPanel;
this.Controls.Add(myPanel);
// to remove the latest panel
panelsAdded.Insert(0, myPanel);
// convert the selected combobox item into a string for label
str_installation = this.cbAnlagen.GetItemText(this.cbAnlagen.SelectedItem);
// create label
Label newLabel = new Label();
newLabel.Name = "testLabel";
newLabel.Text = str_installation;
newLabel.AutoSize = true;
// !!here's the problem with the exception CS0029!!
newLabel.Parent = panel_name;
counterpos_x += 225;
if(counter % 8 == 0)
{
counterpos_y += 175;
counterpos_x = 50;
}
counter++;
}
else
{
MessageBox.Show("Maximale Anzahl an Anlagen erreicht.", "Achtung!");
}
}
Thx。適合我。 – Sakul