【问题标题】:C# 'FindControl' does not exist in the current contextC# 'FindControl' 在当前上下文中不存在
【发布时间】:2018-03-21 16:39:39
【问题描述】:
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;  
        }  
    }  

我收到错误“当前上下文中不存在名称‘FindControl’。我正在尝试根据字符串提供的名称填充文本框数组。

例如;文本框[2] = 变量[x] + "文本框";

我缺少一些命名空间吗?当我查找 FindControl 时,它只是告诉我 NameSpace 是“System.Web.UI”,并且我已将“System.web”添加到我的引用中。

【问题讨论】:

  • 这是一个 Web 项目还是 WinForms?我猜你只需要Controls.Find(...); - 见Find control by name from Windows Forms controls
  • 为什么cast和"as"在同一个句子里?(TextBox)FindControl(Vars[x] + "TextBox") as TextBox
  • 这里FindControl() 看起来是自定义方法而不是控件类方法
  • 这不是实际代码,它不在类中。你把这段代码放在哪里了?
  • 它在一个类中但是我不想复制和粘贴整个代码。它是一个窗体。

标签: asp.net webforms findcontrol


【解决方案1】:

正如@Equalsk 所说,我需要使用 Controls.Find(...);我只是使用了错误的东西。认为我应该将其发布为答案以确保它脱颖而出,因为虽然这可能是一件非常简单的事情,但我(可能像其他人一样)完全不知道这个功能。

` 静态文本框[] 值;

    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;
    }

`

这是更新后的代码。 “当前表单”只是为了让我可以将它用于我的任何表单,因为它位于全局类中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多