开发者

Referring To Named Elements Created Programmatically?

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?


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: the Item property and the Find method. The Item property returns a control with the specified name, whereas the Find method returns a collection of controls. In both cases you would need to cast from a Control to a RichTextBox.

var rt = (RichTextBox)myTableLayoutPanel.Controls.Item["asdf"];

// or

var rts = myTableLayoutPanel.Controls.Find("asdf", false);
foreach (var rt in rts)
    // (RichTextBox)rt ...

EDIT: be sure to check that the result is not null before using it in case the control is not found.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜