2012-10-31 10 views
2

我有一個下拉控制這樣一個asp.net網頁:動態地從下拉列表加載特定的用戶控制在自動回發

<asp:DropDownList ID="TypeDrp" runat="server" 
     OnSelectedIndexChanged="LoadCorrectForm" AutoPostBack="True"> 
    <asp:ListItem>X</asp:ListItem> 
    <asp:ListItem>Y</asp:ListItem> 
    <asp:ListItem>Z</asp:ListItem> 
    </asp:DropDownList> 

    <br /> 

    <asp:PlaceHolder ID="PlaceHolder1" runat="server"> 

    </asp:PlaceHolder> 

我想在PLACEHOLDER1動態加載的控制回發後。這是在文件夾名爲「myControls」是這樣的:

XTypeForm.ascx 
YTypeForm.ascx 
ZTypeForm.ascx 

我應該如何調用和正確使用? 有人告訴我使用某事像這樣:

protected void LoadCorrectForm(object sender, EventArgs e) 
{ 
    string SelectedValue = TypeDrp.SelectedItem.ToString(); 
    Control userControl = GetSpecificUserControl(SelectedValue); 
    PlaceHolder1.Controls.Clear(); // Remove old user control 
    PlaceHolder1.Controls.Add(userControl); 
} 

但它有錯誤,我不知道如何改變它自己的代碼?

+0

問題出在TypeDrp.SelectedItem.ToString() –

+0

Item是文本和值的集合。你在哪裏放置「要加載的控件的名稱」的值。如果它處於下拉列表的值中,則將其替換爲選定的值。 –

回答

0

要加載ASCX用戶控件,使用像這樣的代碼:

if(!Page.IsPostBack) 
{ 
    WebUserControl1 uc = 
    (WebUserControl1) Page.LoadControl("WebUserControl1.ascx"); 
    PlaceHolder1.Controls.Add(uc); 
} 
0


<asp:DropDownList ID="TypeDrp" runat="server" 
    OnSelectedIndexChanged="LoadCorrectForm" AutoPostBack="True"> 
<asp:ListItem Value="XTypeForm.ascx">X</asp:ListItem> 
<asp:ListItem Value="YTypeForm.ascx">Y</asp:ListItem> 
<asp:ListItem Value="ZTypeForm.ascx" >Z</asp:ListItem> 
</asp:DropDownList> 

然後使用

串的SelectedValue = TypeDrp.SelectedValue.ToString ();

它會工作。

+0

我的控制文件位於另一個名爲「myControls」的文件夾中。另外PlaceHolder1.Controls.Add(....)不接受字符串數據類型。但我應該怎樣稱呼控制? – user1787974

+0

string SelectedValue =「foldername /」+ TypeDrp.SelectedValue.ToString(); –

+0

甚至字符串SelectedValue =「〜/」+ TypeDrp.SelectedValue.ToString(); –

0

我不知道它會工作,但你可以嘗試這樣的

string SelectedValue = "foldername/"+TypeDrp.SelectedValue.ToString(); 
var lobjucModelTabs = (SelectedValue)LoadControl("~/yourfolder/"+SelectedValue); 
PlaceHolder1.Controls.Clear(); 
PlaceHolder1.Controls.Add(lobjucModelTabs); 

如果它不工作
,那麼你將不得不使用switch語句艾克這一點。

string filename = TypeDrp.SelectedValue; 
     UserControl userControl; 
     switch (filename) 
     { 
      case "XTypeForm.ascx": 
       UserControl ctrl = (XTypeForm)LoadControl("NewFolder1/XTypeForm.ascx"); 
       PlaceHolder1.Controls.Clear(); 
       PlaceHolder1.Controls.Add(ctrl); 
       break; 
     }