Search code examples
asp.netwebformsfindcontrol

C# 'FindControl' does not exist in the current context


using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
using System.Configuration;  
using System.Data.SqlClient;  
using System.Web.UI;  

public TextBoxes(string query)  
    {  
        String[] Vars = query.Split('@');  
        for (int x = 1;x < Vars.Length;x++)  
        {  
            TextBox tb = (TextBox)FindControl(Vars[x] + "TextBox") as TextBox;  
        }  
    }  

I receive the error "The name 'FindControl' does not exist in the current context. I am trying to fill an array of textboxes depending on the name provided by the string.

e.g; TextBoxes[2] = Vars[x] + "TextBox";

Is there some NameSpace I am missing? As when I look up FindControl it simply tells me the NameSpace is "System.Web.UI" and I have added "System.web" to my references.


Solution

  • As @Equalsk had said all I needed to use Controls.Find(...); I was simply using the wrong thing. Figured I should post this as an answer to ensure it stands out, as while it may have been a very simple thing to do, I (like others may be) was completely unaware of this feature.

    ` static TextBox[] Values;

        public static TextBox[] TextBoxes(string query, Form Current)
        {
            String[] Vars = query.Split('@');
    
            String[] NewVars = new String[Vars.Length - 1];
            Values = new TextBox[Vars.Length - 1];
    
            for (int x = 0; x < Vars.Length - 1; x++)
            {
                NewVars[x] = Vars[x + 1].Remove((Vars[x + 1].Length - 1));
                Values[x] = Current.Controls.Find(NewVars[x] + "TextBox", true).FirstOrDefault() as TextBox;
            }
    
            return Values;
        }
    

    `

    This is the updated code. The "Form Current" is simply to allow me to use this for any of my forms as I have it situated in a global class.