2012-05-24 35 views
1

我正面臨一個問題。我在我的應用程序中設置了一些枚舉。像將字符串轉換爲Enum而不知道它是C類型的#

public enum EnmSection 
{ 
    Section1, 
    Section2, 
    Section3 
} 

public enum Section1 
{ 
    TestA, 
    TestB 
} 

public enum Section2 
{ 
    Test1, 
    Test2 
} 

EnmSection是主枚舉,它包含另一個在它下面聲明的枚舉(作爲字符串)。現在我必須在下拉菜單中填寫EnmSection的值。我已經完成了。 就像這個...

drpSectionType.DataSource = Enum.GetNames(typeof(EnmSection)); 
drpSectionType.DataBind(); 

現在我的下拉有值:Section1,Section2,Section3

問題是:

我還有一個下拉drpSubSection。現在我想填充這個下拉列表,無論我在drpSectionType中選擇了什麼。

對於ex如果我選擇了drpSectionType中的Section1,那麼drpSubsection應該包含值 TestA,TestB。像這樣:

protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string strType = drpSectionType.SelectedValue; 
    drpSubsection.DataSource = Enum.GetNames(typeof()); 
    drpSubsection.DataBind(); 
} 

這裏typeof()期待enum.But我得到選定的值作爲字符串。我怎樣才能實現這個功能。

感謝

回答

3

如果你引用包含有一個名爲Section1值的另一枚舉的組件?

你只需要嘗試所有你關心的枚舉,一次一個,看看哪一個可以工作。你可能會想要使用Enum.TryParse

0
drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType)); 

如果枚舉在另一個程序集,(即他們不是在mscorlib程序或當前組件),你需要提供AssemblyQualifiedName。最簡單的方法是查看typeof(Section1).AssemblyQualifiedName,然後修改代碼以包含所有必要的部分。該代碼將是這個樣子,當你完成:

drpSubsection.DataSource = Enum.GetNames(Type.GetType("Your.Namespace." + strType + ", MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089")); 
+0

不工作。它給我錯誤: - 值不能爲空。 參數名稱:enumType – VSoni

+0

這意味着Type.GetType沒有找到類型。你確定你有正確的枚舉名稱空間嗎? –

+0

是的:)。你能爲我提供任何工作解決方案嗎? – VSoni

0

像這樣的事情可能會奏效,但你必須做一些異常處理:

protected void drpSectionType_SelectedIndexChanged(object sender, EventArgs e) 
{  
    string strType = drpSectionType.SelectedValue;  
    EnmSection section = (EnmSection)Enum.Parse(typeof(EnmSection), strType); 
    drpSubsection.DataSource = Enum.GetNames(typeof(section));  
    drpSubsection.DataBind(); 

} 
+0

不工作。我不能在typeof()---> Enum.GetNames(typeof(section)); – VSoni

0

這可能是一個比最高位但如果將綁定的IEnumItem數組綁定到您的下拉列表並將其設置爲顯示其顯示文本,它會起作用。

public interface IEnumBase 
{ 
    IEnumItem[] Items { get; } 
} 

public interface IEnumItem : IEnumBase 
{ 
    string DisplayText { get; } 
} 

public class EnumItem : IEnumItem 
{ 
    public string DisplayText { get; set; } 
    public IEnumItem[] Items { get; set; } 
} 

public class EnmSections : IEnumBase 
{ 
    public IEnumItem[] Items { get; private set; } 

    public EnmSections() 
    { 
    Items = new IEnumItem[] 
    { 
     new EnumItem 
     { 
     DisplayText = "Section1", 
     Items = new IEnumItem[] 
     { 
      new EnumItem { DisplayText = "TestA" }, 
      new EnumItem { DisplayText = "TestB" } 
     } 
     }, 
     new EnumItem 
     { 
     DisplayText = "Section2", 
     Items = new IEnumItem[] 
     { 
      new EnumItem { DisplayText = "Test1" }, 
      new EnumItem { DisplayText = "Test2" } 
     } 
     } 
    }; 
    } 
} 
相關問題