close
            
        
            http://www.dotblogs.com.tw/mis2000lab/archive/2014/03/24/dropdownlist_selectedindex_20140324.aspx
DropDownList使用者未曾挑選(沒選取)任何一個子項目,該如何警示?
DropDownList使用者未曾挑選(沒選取)任何一個子項目,該如何警示?
根據 msdn網站的說明:
SelectedIndex 屬性  -- 清單中選取項目的最低序數索引。 預設值為 -1,指出沒有選取任何項目。
經過測試
RadioButtonList / CheckBoxList / ListBox都可以這樣使用(如同下面程式),來偵測 User沒有點選任何一個項目
唯獨 DropDownList做不到???
    protected void Button3_Click(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedIndex == -1)
        {
            Label1.Text = "<br />[Button3]--RadioButtonList1尚未選取";
        }
        else
        {
            Label1.Text = "<br />[Button3]--RadioButtonList1--" + RadioButtonList1.SelectedValue;
        }
    }
DropDownList當您按下按鈕之後,總是會抓到第一個子選項(selectedIndex = 0)
即使您根本沒有點選它、
也沒有設定它(第一個子選項)是預設選項 (.Selected)
不管您是否設定 DropDownList的 AutoPostBack都一樣。
(點選圖片,可以連結到解答)
解決方法:
        <asp:DropDownList ID="DropDownList2" runat="server"
                               OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
                <asp:ListItem Value="0">未選取</asp:ListItem>
                <asp:ListItem Value="X111_Vaue">X111</asp:ListItem>
                <asp:ListItem Value="X222_Vaue">X222</asp:ListItem>
                <asp:ListItem Value="X333_Vaue">X333</asp:ListItem>
                <asp:ListItem Value="X444_Vaue">X444</asp:ListItem>
        </asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
             ControlToValidate="DropDownList2"
             ErrorMessage="RequiredFieldValidator未選取!" ForeColor="Red" InitialValue="0"></asp:RequiredFieldValidator>
        </p>
        <p>
        <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />  </p>
 
............................. 寫信給我,mis2000lab (at) yahoo.com.台灣........................................................
............................. facebook社團 https://www.facebook.com/mis2000lab ............................
............................. Google+ https://plus.google.com/100202398389206570368/posts ..............
http://www.dotblogs.com.tw/mis2000lab/archive/2014/03/24/dropdownlist_selectedindex_20140324.aspx
DropDownList使用者未曾挑選(沒選取)任何一個子項目,該如何警示?
文章標籤
        全站熱搜
        
 留言列表