繁体   English   中英

如何访问ASP.NET中的RadioButtonList项目?

[英]How to access RadioButtonList items in ASP.NET?

假设我在C#中有一个RadioButtonList。 此列表包含最喜欢的水果的选择器(按字母顺序排列):

Favorite Fruits:
    ( )  Apple
    ( )  Banana
    ( )  Pineapple
    ( )  Pomegranate

...假设我有一个方法,只需单击一下按钮,即可打印出有关您最喜欢的水果的事实:

private void FruitFactsButton_OnClick(arguments){

    switch( favoriteFruits.SelectedIndex ){

        case 0:      // Apple
          doStuffForApple();
        break;

        case 1:      // Banana
          doStuffForBanana();
        break;

        case 2:     // Pineapple
          doStuffForPineapple();
        break;

        case 3:    // Pomegranate
          doStuffForPomegranate();
        break;
    }

}

假设我的代码库中有数十个开关/案例,这取决于选择了哪个favoriteFruits元素。

如果我决定将元素添加到此列表中(而不是在结尾处),则必须手动查找每个开关/案例并更新索引(添加Banana会迫使我对KiwiPineapplePomegranate的索引+1 ,如果我想按字母顺序排列所有内容。)

有没有一种方法可以将索引作为枚举值引用? 在这种情况下,我能做些什么吗?

    switch( favoriteFruits.SelectedIndex ){
        case favoriteFruits.getEnumConstants.APPLE:
            doStuffForApple();
        break;

我知道有一个RadioButtonList.Items访问器,但是我很困惑从那里去哪里。 任何帮助表示赞赏!

有没有一种方法可以将索引作为枚举值引用?

根据您的整个帖子,看来,“您需要知道单击的内容并根据该内容采取措施”。 然后,是否要针对索引或控件的值进行测试并不重要。 如果是这样,那么执行以下操作应该会有所帮助:

// declare the items, no need to set values
public enum FavoriteFruits {
    Banana,
    Apple, }

// bind the enum to the control
RadioButtonList1.DataSource = Enum.GetValues(typeof(FavoriteFruits)); 
RadioButtonList1.DataBind();

// this is needed because SelectedValue gives you a string...
var selectedValue = (FavoriteFruits)Enum.Parse(typeof(FavoriteFruits), 
   RadioButtonList1.SelectedValue, true); 
//...then you can do a switch against your enum
switch (selectedValue )
{
    case FavoriteFruits.Apple:
        doStuffForApple();
        break;
    case FavoriteFruits.Banana:
       doStuffForBanana();
       break;
}

确保验证SelectedValue因为如果未选择任何内容,它将引发异常。

如果我理解正确,您会使用枚举吗?

enum Fruits{
    Apple = 0,
    Banana = 1,
    Pineapple = 2,
    Pomegranate = 3
};

switch( favoriteFruits.SelectedIndex ){
    case Fruits.Apple:
        doStuffForApple();
    break;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM