C# - 在运行时填充数据结构,并引用设计时添加到 TableLayoutPanel 的按钮

发布于 2024-08-10 11:05:18 字数 560 浏览 7 评论 0原文

我使用的是 Visual C# 2008 Express 版本。

如果在设计时我有一个表单 [myMainForm],
我添加了一个 TabControl [myTabControl],
myTabControl 有一个 tabPage [myTabPage],
并在此 tabPage 中添加了一个 tableLayoutPanel [myTableLayoutPanel],
我在 myTablelayoutPanel 中添加了十个按钮(button1、button2、button3 等)。

在运行时,我想用对我添加到 myTableLayoutPanel 的所有十个按钮的引用来填充数据结构。我希望以最简单、最有效的方式处理对按钮的引用。 for...next 循环与数组结合是解决该问题的最佳方法吗?

我意识到我可以以编程方式将按钮添加到面板中,但如果我这样做,我还必须在代码中调整它们的视觉设置,我宁愿避免这样做,以便使我的代码尽可能干净和简单。

如果有人可以发布几行代码来让我继续下去,我将不胜感激。

感谢您花时间阅读本文。快乐编码。

问候,

事情

I am using Visual C# 2008 Express edition.

If at design time I have a form [myMainForm],
to which I have added a TabControl [myTabControl],
and myTabControl has a single tabPage [myTabPage],
and to this tabPage I have added a tableLayoutPanel [myTableLayoutPanel],
and to myTablelayoutPanel I have added ten buttons (button1, button2, button3, etc).

At runtime I want to populate a data structure with references to all the ten buttons I have added to myTableLayoutPanel. I want to work with the references to the buttons in the simplest, most efficient way possible. Is a for...next loop in conjunction with an array the best approach to tackle the problem?

I realise that I could add the buttons programmatically to the panel, but if I do that I will have to tweak their visual settings in code as well which I would rather avoid in order to keep my code as clean and simple as possible.

If someone could post a few lines of code to get me going on this I'd be grateful.

Thanks for taking the time to read this. Happy coding.

Regards,

The Thing

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请叫√我孤独 2024-08-17 11:05:18

在 C#3(在 VS 2008 中)中,您可以使用数组初始值设定项语法设置编译时数组:

var buttons = new [] { button1, button2, ... button10 };

或者,您可以反映所有字段并过滤按钮,沿着

using System.Linq;

// tlp being your TablelayoutPanel instance
var buttons = tlp.GetType().GetFields().Select(f => f.GetValue(tlp)).Where(v => v is Button).ToArray();

This gets all the Buttons --如果您想过滤掉除某些已知命名之外的这些字段,您可能需要在 Select 之前添加 Where(f => SomeTestOn(f.Name)) 过滤器图案表明它们是您真正想要的按钮。

In C#3 (in VS 2008), you could set up a compile-time array using the array initializer syntax:

var buttons = new [] { button1, button2, ... button10 };

alternatively, you could reflect on all the fields and filter the buttons, along the lines of

using System.Linq;

// tlp being your TablelayoutPanel instance
var buttons = tlp.GetType().GetFields().Select(f => f.GetValue(tlp)).Where(v => v is Button).ToArray();

This gets all the buttons -- you might want to add a Where(f => SomeTestOn(f.Name)) filter before the Select if you want to filter out those fields except with some known naming pattern indicating that they are the buttons you actually want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文