Is textBox24
apart of the current control or possibly apart of a nested control?
Index of control is -1 in C#
Hemanth B
886
Reputation points
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.
Accepted answer
-
P a u l 10,406 Reputation points
2021-12-15T17:16:03.147+00:00
2 additional answers
Sort by: Most helpful
-
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"; }
-
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,
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 }