Index of control is -1 in C#

Hemanth B 886 Reputation points
2021-12-15T17:14:06.123+00:00

Hi, I am trying to get the index of a textbox control in WinForms, so I am using this:
var index = Controls.IndexOf(textBox24);
MessageBox.Show(index.ToString());
Now when I run the app, and click on the textbox, it shows the index as -1. Why? Because of the index being -1, I am having problems in using the textbox in some piece of code.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,266 questions
{count} votes

2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2021-12-15T17:32:42.607+00:00

    Why not use this

    var results = Controls.Find("textBox24", true);
    if (results.Length == 1)
    {
        // found it
        ((TextBox)results[0]).Text = "OK";
    }
    else
    {
        // did not find it
    }
    

    Or

    if (Controls.Find("textBox24", true).FirstOrDefault() is TextBox textBox)
    {
        textBox.Text = "OK";
    }
    
    0 comments No comments

  2. Petrus 【KIM】 456 Reputation points
    2021-12-16T06:06:44.467+00:00

    If the text box may have been positioned as shown in the following picture,

    158141-image.png

    Then, you can use this.

    private void button1_Click(object sender, EventArgs e)  
    {  
        var index = Controls.IndexOf(this.textBox24);  
        MessageBox.Show(index.ToString()); // -1  
    
        var i1 = groupBox1.Controls.IndexOf(this.textBox1);  
        MessageBox.Show(i1.ToString());  
    
        var v1 = Controls.Find(this.textBox1.Name, true).FirstOrDefault();  
        MessageBox.Show(v1.TabIndex.ToString()); // Not -1  
    }  
    
    0 comments No comments