You must Sign In to post a response.
  • Category: .NET

    How to Get Control Name in Windows Application

    Hi

    I have implemented KeyPress Event in Windows C# Application. When i press Enter Key in form_Keydown event i need how To get Control name .
  • #749386
    Hi Jay,

    I am not sure to get the control names. But we can get the "Text" (assigned name for each controls) of the each controls.

    you can try the below code.

    private void button2_Click(object sender, EventArgs e)
    {
    Control.ControlCollection allcont = this.Controls;

    foreach (Control tc in allcont)
    {
    if (tc != null)
    {
    MessageBox.Show(tc.Text, "Index numb: " + allcont.GetChildIndex(tc, false));
    }
    }
    }

    -----------------------------------------------------------------------------
    Regards,
    Gopi A.
    +91 9894315571
    Skype:gopi.net
    http://asaigopi-dotnet.blogspot.in/

  • #749484
    In the below code, I am showing you how to get the control id when you enter any key in the textbox control and handle the keypress event of the textbox.

    private void txtstatus_KeyPress(object sender, KeyPressEventArgs e)
    {
    TextBox txt = (TextBox)sender;
    MessageBox.Show(txt.Name);
    }

    In the above code. TextBox id is txtstatus. we are typecasting sender to TextBox and getting its name through the Name property of the textbox.

    Miss. Jain
    Microsoft Certified Technology Specialist in .Net

  • #749492
    Hai JayaKumar,
    The ControllCollection class will have all the controls of the Form so you can retrieve them by using this collection.
    You can use the foreach loop to get all the controls like below as well:

    foreach(var c in this.Controls)
    {
    if(c.GetType().Name == "TextBox")
    {
    // do something
    }
    }

    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #749649
    You can use the sender argument, that is the Control (the button in this case) that has raised the click event:

    var button = (Button)sender;
    button.Name ...

    N.B.
    In case you have subscribed other controls (e.g. panels etc) to the same event handler,
    you can check if the sender is a button using the asoperator:

    var button = sender as Button;
    if (button != null)
    {
    button.Name ...
    ...
    }

    and

    Control control = (Control) sender;
    String name = control.Name;

    Reference:
    http://stackoverflow.com/questions/7644131/getting-control-name-for-an-event
    http://msdn.microsoft.com/en-us/library/aa457091.aspx

    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in


  • Sign In to post your comments