引用以编程方式创建的命名元素?
我有一个使用以下代码以编程方式创建的 RichTextBox:
RichTextBox RT = new RichTextBox();
RT.Name = "asdf";
RT.Text = "blah";
TableLayoutPanel.Controls.Add(RT,0,0);
现在假设我要修改 RT 的文本,它的名称是“asdf”,Visual Studio 不允许我编写 asdf.Text =“haha”,因为 asdf 不还不存在。
如何专门抓取“asdf”并设置其文本?因为这个RichTextBox位于特定的单元格中,所以我可以根据它的单元格坐标来抓取它吗?
I have a RichTextBox created programmatically with the following code:
RichTextBox RT = new RichTextBox();
RT.Name = "asdf";
RT.Text = "blah";
TableLayoutPanel.Controls.Add(RT,0,0);
Now let's say I want to modify the text of RT, and it's name is "asdf", Visual Studio won't allow me to write asdf.Text = "haha" because asdf doesn't exist yet.
How can I grab "asdf" specifically and set its text? Because this RichTextBox is in a specific cell, can I grab it based on its cell coordinates?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够通过 TableLayoutPanel.Controls 属性获取对它的引用,该属性返回一个 TableLayoutControlCollection。该类提供了两种按名称查找控件的方法:
Item 属性
和
查找
方法。Item
属性返回具有指定名称的控件,而Find
方法返回控件的集合。在这两种情况下,您都需要从Control
转换为RichTextBox
。编辑:在使用之前请务必检查结果是否不为空,以防找不到控件。
You should be able to get a reference to it via the
TableLayoutPanel.Controls
property, which returns a TableLayoutControlCollection. That class provides two ways to locate a control by name: theItem
property and theFind
method. TheItem
property returns a control with the specified name, whereas theFind
method returns a collection of controls. In both cases you would need to cast from aControl
to aRichTextBox
.EDIT: be sure to check that the result is not null before using it in case the control is not found.
嗯...您确实实例化了 RichTextBox 并拥有可以使用的引用;在你的例子中它被称为“RT”。
现在,您可能已经在方法中完成了此操作,因此它的作用域是本地的,并且在您需要时不再可用。因此,您可以通过将其分配给您可以访问的某个成员来以某种方式保存该引用。例如,如果您有很多并且希望通过名称进行区分,则可以将其粘贴到
Dictionary
中。或者你可以把它放在一些静态变量中;有多种选择,每种选择都有自己的优点和缺点。您可能不想做的一件事是遍历控件树,查找具有您指定名称的控件。但如果你真的愿意的话,你也可以这样做。
Well... you did instantiate the RichTextBox and have a reference that you can use; it's called "RT" in your example.
Now, likely you've done this in a method so it was locally scoped and is no longer available when you want it. So you save that reference somehow by assigning it to some member you can access. If you have a lot of them and want to differentiate by name somehow, you might stick it into a
Dictionary<string, RichTextBox>
, for example. Or you could put it in some static variable; there are numerous options, each with their own pros and cons.The one thing you probably don't want to do is walk the control tree looking for the control with the name you specified. But you could also do that, if you really wanted to.