简体   繁体   English

在设计模式下无法获取UserControl名称

[英]Unable to get UserControl name in design mode

My code requires to get the control name in user control Load event, problem is i get the control name in assembly, not the name i assign in the form, but if i run the project i get the control name properly. 我的代码要求在用户控件Load事件中获取控件名称,问题是我在程序集中获取控件名称,而不是我在表单中分配的名称,但是如果我运行项目,则可以正确获取控件名称。

To test, just add following code to any user control 要进行测试,只需将以下代码添加到任何用户控件中

Private Sub GridX_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    MsgBox(Me.Name)
End Sub

At runtime this gives ControlName1 在运行时,这提供了ControlName1

At design time this gives ControlName 在设计时,这将提供ControlName

how can I get the ControlNameX at runtime? 如何在运行时获取ControlNameX


To make it more clear, add two controls in the form, you will see that name of the control in design mode are the same.. unlike in runtime mode.. 为了更加清楚,在窗体中添加两个控件,您将看到在设计模式下该控件的名称是相同的..与在运行时模式下不同。

If you add a property to your user control like this: 如果将属性添加到用户控件中,如下所示:

// Note: code in C#
public string ControlName
{
    get
    {
        return Name;
    }
    set
    {
        Name = value;
        MessageBox.Show(value);
    }
}

You compile it and you add it to the form, you have a ControlName property in your designer. 您对其进行编译并将其添加到窗体,您的设计器中就有一个ControlName属性。 If you change the name in the designer, the new name shows up. 如果在设计器中更改名称,则会显示新名称。 Instead of the MessageBox.Show() you want to call an eventhandler, so you can do something with the new name. 您不想调用MessageBox.Show()而是要调用事件处理程序,因此可以使用新名称进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM