C# 在 if 语句中使用下拉列表的选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19390413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:52:47  来源:igfitidea点击:

Using the selected value of a dropdown list in an if statement

c#asp.net

提问by John

I'm trying to select the value from this drop down list to use in an if statement so that I can then do calculations based on which choice is chosen. I'm not sure if this is the right way to do it, any help would be much appreciated!

我正在尝试从此下拉列表中选择要在 if 语句中使用的值,以便我可以根据选择的选项进行计算。我不确定这是否是正确的方法,任何帮助将不胜感激!

   <asp:DropDownList ID="ddlHours" runat="server">
                <asp:ListItem >Select</asp:ListItem>
                <asp:ListItem >Part-Time</asp:ListItem>
                <asp:ListItem >Full-Time</asp:ListItem>
            </asp:DropDownList>

const int PART_TIME = 15;
                const int FULL_TIME = 25;
                double fee = 0;

                if (ddlHours.SelectedItem.Value == "Part-Time")
                {
                    CalculatePartTime(PART_TIME, fee);

                }

                else if (ddlHours.SelectedItem.Value == "Full-Time")
                {
                    CalculateFullTime(FULL_TIME, fee);
                }

                lblAnswer.Text = String.Format("{0}",fee);

采纳答案by Jonysuise

I would use :

我会用:

if (ddlHours.SelectedItem.Text == "Part-Time")

回答by COLD TOLD

it looks like you are not looking for value you are looking for text

看起来您不是在寻找价值,而是在寻找文本

if(ddlHours.SelectedItem.Text == "Part-Time")

回答by Chris Brickhouse

if you open to javascript/jquery, you could do this:

如果你打开 javascript/jquery,你可以这样做:

var PART_Time = 15;
var FULL_TIME = 25;
var fee = 0;

$('#ddlHours').change(function() {
    var $this = $(this);
    if ($this.val() == 'Part-Time') {
        $('#labelAnswer').val(CalculatePartTime(PART_TIME, fee);
    }
    else {
        $('#labelAnswer').val(CalculateFullTime(FULL_TIME, fee);
    }
});

i know this doesn't answer your specific question but this would reduce postbacks.

我知道这不能回答您的具体问题,但这会减少回发。