[英]dynamically add content to tabpages
Am trying to dynamically add listboxes and pictures to dynamically created tabpages within a tabcontrol using c#. 我试图使用c#将列表框和图片动态添加到tabcontrol中动态创建的tabpage。 The form has a button which creates dynamically tabpages to the tabcontrol and also adds inside listboxes and some other content.
表单具有一个按钮,该按钮可动态创建tab控件的tabpage,还添加内部列表框和其他一些内容。
The problem is when I hit the button the second time it deletes everything from the previous tab and adds it to the last one. 问题是,当我第二次按下按钮时,它将删除上一个选项卡中的所有内容并将其添加到最后一个选项卡中。
private void AddNewPr_Click(object sender, EventArgs e)
{
TabPage tab = new TabPage();
ListBox list = new ListBox();
ListBox list2 = new ListBox();
PictureBox pictureBox = new PictureBox();
PictureBox pictureBox2 = new PictureBox();
tab.Name = "tabPage" + n;
tab.Text = "Property " + n;
tabControl1.Controls.Add(tab);
list.Items.AddRange(new object[] {
"Id",
"Name"
});
//more list properties here///
//other items here created/////
tab.Controls.Add(list);
tab.Controls.Add(list2);
tab.Controls.Add(pictureBox);
n++;
}
I also declare an integer incrementor so that all new content have their own name identity. 我还声明了一个整数增量器,以便所有新内容都具有自己的名称标识。 The other problem I have is I cant access the pictureBox click event handler which is also created dynamically.
我遇到的另一个问题是我无法访问也动态创建的pictureBox click事件处理程序。
Thanks for your help..!! 谢谢你的帮助..!!
To access the newly created items ( list
, list2
) from a different method in the class, you'll need to create class-level variables. 要从类中的其他方法访问新创建的项目(
list
, list2
),您需要创建类级变量。 For example, expanding your sample above a little: 例如,将样本扩大一点:
public class MyForm : Form
{
//Class-level variables, accessible to all methods in the class
private ListBox _list;
private ListBox _list2;
private void AddNewPr_Click(object sender, EventArgs e)
{
TabPage tab = new TabPage();
_list = new ListBox();
_list2 = new ListBox();
PictureBox picBox = new PictureBox();
picBox.Click = picBox_Click;
//More stuff here
//Add the controls
tabControl1.Controls.Add(tab);
tab.Controls.Add(list);
tab.Controls.Add(list2);
tab.Controls.Add(pictureBox);
}
private void picBox_Click(object sender, EventArgs e)
{
//_list and _list2 are in scope here because they are defined at the class-level
_list.Items.AddRange(new object()["Id", "Name"]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.