2017-12-27 446 views
0

我正在编写一个ASPX/C#应用程序。它使用gridviews和模板字段以及控件。为了访问动态控件,我使用了findcontrol方法,它一切正常。C#查找控制,铸造,优雅代码

但随着应用程序变得越来越大,我可以看到代码来查找在不同的功能/按钮点击事件中重复使用的控件。我认为最好创建一个通用函数,该函数根据传递给它的参数找到控件。我是一个C#初学者,需要知道这是否可能?或者必须指定控件类型?

这就是我正在使用的(该功能未经过测试,因此可能是一个有缺陷的想法)。

在点击事件代码:

Button btn = (Button)sender; 
    GridViewRow gvr = (GridViewRow)btn.NamingContainer; 
    TextBox details = gvr.FindControl("detailsText") as TextBox; 
    //do something with details 
    TextBox cusID = gvr.FindControl("TextBox2") as TextBox; 
    // do something with cusID 

我想写

protected Control Returncontrol(GridViewRow gvr, String ControlName) 
{ 
    TextBox aCon = gvr.FindControl(ControlName) as TextBox; 
    // This bit is what I am not sure about. Is possible to find the control without specifying what type of control it is? 
    return aCon; 
} 

功能这是我的目标是使用功能:

Returncontrol(gvr, TextBox2).text ="Something"; 
+0

' “TextBox2中”'?首先解决它。 –

+0

这是伪代码,我正在讨论作为一个概念的想法。 – SANM2009

+0

这里有点不清楚你在这里试图做什么以及你的实际问题是什么。由于'TextBox'继承自'Control',因此您应该能够从'Returncontrol'(应该是'ReturnControl')函数中返回它。然而,更好的选择可能是使用通用函数'T ReturnControl '来查看? –

回答

3

您可以创建一个方法使用泛型类型参数,调用者可以指定类似的控制类型:

protected TControl Returncontrol<TControl>(GridViewRow gvr, String ControlName) 
                    where TControl : Control 
{ 
    TControl control = gvr.FindControl(ControlName) as TControl; 

    return control; 
} 

现在,您将使用它像:

TextBox txtBox = ReturnControl<TextBox>(grid1,"TextBox1"); 

,现在你可以访问TextBox类型可用的属性和方法:

if(txtBox!=null) 
    txtBox.Text ="Something"; 

您还可以创建一个扩展方法在GridViewRow类型这为一个选项,如:

public static class GridViewRowExtensions 
{ 
    public static TControl Returncontrol<TControl>(this GridViewRow gvr, String ControlName) where TControl : Control 
    { 
     TControl control = gvr.FindControl(ControlName) as TControl; 

     return control; 
    } 
} 

,现在你可以使用GridViewRow实例直接调用它:

TextBox txtBox = gvr.ReturnControl<TextBox>("TextBox1"); 

if(txtBox!=null) 
    txtBox.Text="Some Text"; 

希望它让你对如何实现你在找什么想法。

+0

我想实现选项一,我得到错误说;无法将web.ui.control转换为TControl,而TControl也不能与as运算符一起使用。 – SANM2009

+0

你需要添加约束如:'受保护TControl返回控制(GridViewRow gvr,字符串ControlName) 其中TControl:Control',更新后的帖子太 –

+0

谢谢。全部排序。这正是我所期待的。 – SANM2009

2

你可以创建一个扩展方法的静态辅助类:

public static class ControlHelper 
{ 
    public static T GetCtrl<T>(this Control c, string name) where T : Control 
    { 
     return c.FindControl(name) as T; 
    } 
} 

然后,您可以使用它像这样:

using _namespace_of_ControlHelper_ ; 

// ... 
TextBox txtBox = gvr.GetCtrl<TextBox>("TextBox1");