[英]Adding buttons programmatically to a TabControl (TabPage)
我读了这个主题(在C#中向TabControl选项卡添加按钮),但我不明白为什么下面的代码仅向选项卡页面添加一个按钮。 我显然已经调试了foreach正常工作。
foreach (string line in File.ReadAllLines(@"C:\quicklauncher.ini"))
{
TabPage page = new TabPage(foldername);
DirectoryInfo d = new DirectoryInfo(line);
foreach (FileInfo file in d.GetFiles("*.*"))
{
Button button = new Button();
button.Text = file.Name;
button.Click += new EventHandler(button_Click);
page.Controls.Add(button);
}
tabControl.TabPages.Add(page); //add our tab page to the tab control
}
谢谢,史蒂夫
您以为它只为您添加了一个按钮,但实际上却没有,它为您添加了所有按钮,但是这些按钮具有相同的位置 (默认为(0,0))。 这就是为什么您确实认为只有1个按钮(因为您只在其他按钮的顶部看到了最后一个按钮)。
您已将按钮自动添加到标签页,因此您应该有一些规则来定位它们,我不确定该规则是什么,但是我想您想将它们垂直排列(仅作为示例),我将更正您的按钮代码来实现这样的事情,至少您会看到它起作用,并且实际上所有按钮都是正常添加的:
//you need some variable to save the next Top for each new button:
//let's call it nextTop:
int nextTop = 0;
foreach (FileInfo file in d.GetFiles("*.*"))
{
Button button = new Button { Top = nextTop,
Text = file.Name };
button.Click += new EventHandler(button_Click);
page.Controls.Add(button);
nextTop += button.Height + 5; //it's up to you on the
//Height and vertical spacing
}
//...
您还可以尝试使用诸如FlowLayoutPanel
和TableLayoutPanel
类的布局控件来包含所有按钮,它们可以按您希望的某种方式帮助您安排按钮,只需尝试一下即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.