0

I have two drop down lists. I need a selection made in the second one if there is a selection in the first one.

if((ddl1.SelectedIndex > -1 ) != (ddl2.SelectedIndex > -1))
{
    this.lblError.Visible = true;
}

So basically if the there is a selection in the first one but not the second one then error.

Would it be the drop down it's self??

      <asp:DropDownList ID="ddlRate1" runat="server">
                   <asp:ListItem Value="">(Select)</asp:ListItem>
                   <asp:ListItem>Initial</asp:ListItem>
                   <asp:ListItem>Moderate</asp:ListItem>
                     </asp:DropDownList>
4

3 に答える 3

1
if((ddl1.SelectedIndex > -1 ) && !(ddl2.SelectedIndex > -1))
{
    this.lblError.Visible = true;
}

これは、「最初のものでは選択されていますが、2番目のものでは選択されていません」と言ったことの翻訳にすぎません。最初のものには値があり(-1より大きい) 2番目のものには値がありませ価値。

2 番目の値に使用するなど、いくつかの方法でこれをリファクタリングできますddl2.SelectedIndex == -1が、このコードは、どのように機能するかを説明したとおりに読み取られ、実際には何も問題がないため、多くの価値があります。私の目。

于 2012-09-26T19:27:30.227 に答える
1

あなたのコメントから更新、再度更新..

これが、もともと 2 つの if ステートメントで記述した理由です。

if((ddl1.SelectedIndex > 0  ) {   

     //code to read value from ddl1

             if (ddl2.SelectedIndex == 0))
            {
                this.lblError.Visible = true;
                // or maybe a bool 'IsValid'  maybe..
            }
}

次に、フォーム全体にこのようなコードがあると仮定すると、最後に実行できます

if ( this.lblError.Visible == true) {  // code to handle invalid form }

また..

if ((ddl1.SelectedIndex > 0 )  && (ddl2.SelectedIndex == 0)) {
     this.lblError.Visible = true;
}

トラブルシューティングのためにこれを試してください - if ステートメントの前に

 this.lblError.Visible = true;
 this.lblError.Text = "ddl1 : " + ddl1.SelectedIndex.ToString() + " ddl2 : " + ddl2.SelectedIndex.ToString();
于 2012-09-26T19:24:38.887 に答える
0

あなたはこれを行うことができます

 <asp:DropDownList ID="ddl1" runat="server">
               <asp:ListItem Value="">(Select)</asp:ListItem>
               <asp:ListItem Value="Initial">Initial</asp:ListItem>
               <asp:ListItem Value="Moderate">Moderate</asp:ListItem>
                 </asp:DropDownList>

C#

if((ddl1.SelectedValue.Length > 0 ) && (ddl2.SelectedValue.Length == 0))
{
    this.lblError.Visible = true;
}
于 2012-09-26T20:36:30.217 に答える