2017-12-27 895 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");