2009-07-18 43 views
0

有:當模板使用FormView時,是否可以靜態引用控件?

<asp:FormView ID="frmEmployee" runat="server"> 
    <EditTemplate> 
     <asp:TextBox ID="txtFirstName" runat="server" /> 
    </EditTemplate> 
</asp:FormView> 

一個使用的FindControl引用txtFirstName文本框的代碼隱藏文件:

VB.Net 
Dim txtFirstName As TextBox = CType(Page.FindControl("txtFirstName"), TextBox) 
txtFirstName.Text = "George" 

C# 
TextBox txtFirstName = (TextBox)Page.FindControl("txtFirstName"); 
txtFirstName.Text = "George"; 

有靜態引用這個控制,而無需使用的FindControl的方法嗎?

VB.Net 
txtFirstName.Text = "George" 

C# 
txtFirstName.Text = "George"; 

回答

0

不是我所知道的。您是否試圖靜態引用,以便編譯器驗證您是否在編譯時引用了有效的控件,或試圖靜態引用它,以便使用起來更容易?

如果是後者,我最終只是創建一個函數,爲我在FormView中獲取和設置值。這裏是基本的佈局:

public string GetValue(string id, ref FormView fv) 
{ 
    Control ctrl = fv.FindControl(id); 
    string value = ""; 

    if(ctrl is TextBox) 
    { 
     TextBox tb = (TextBox)ctrl); 
     value = tb.Text; 
    } 
    else if(ctrl is DropDownList) 
    { 
     DropDownList ddl = (DropDownList)ctrl; 
     value = ddl.SelectedValue; 
    } 
    else if(... 
    ... 
    ... 

    return(value); 
} 

public void SetValue(string id, string value, ref FormView fv) 
{ 
    Control ctrl = fv.FindControl(id); 

    if(ctrl is TextBox) 
    { 
     TextBox tb = (TextBox)ctrl); 
     tb.Text = value; 
    } 
    else if(ctrl is DropDownList) 
    { 
     DropDownList ddl = (DropDownList)ctrl; 
     ddl.SelectedValue = value; 
    } 
    else if(... 
    ... 
    ... 
} 

希望有所幫助。

相關問題