我有这样的下拉列表:
<asp:DropDownList ID="CompaniesDropDownList" runat="server" DataSourceID="CompaniesObjectDataSource"
DataTextField="NameLang1" DataValueField="CompanyID" AppendDataBoundItems="True"
AutoPostBack="true">
<asp:ListItem Value="0" Text="select a company"></asp:ListItem>
</asp:DropDownList>
<asp:ObjectDataSource ID="CompaniesObjectDataSource" runat="server" TypeName="HRCompany"
SelectMethod="GetList"></asp:ObjectDataSource>
<asp:CustomValidator ID="CompanyCustomValidator" runat="server" ErrorMessage="select a company"></asp:CustomValidator>
我正在设置所选的值:
CompaniesDropDownList.SelectedItem.Value = "3";
它正在发挥作用。
设置此值后,我正在检查条件,所选索引或值是否为:
if (CompaniesDropDownList.SelectedValue == "0")
或
if (CompaniesDropDownList.SelectedIndex == 0)
总是如此。虽然在前端的下拉列表中,选择了值为3的项目。
如何获取此下拉列表的选定索引?
请建议
答案 0 :(得分:0)
这就是我想要的。我想从db获取值并设置为selected 页面加载索引。
protected void Page_Load(object sender, EventArgs e)
{
try {
if (!IsPostBack) {
LoadValues(); // this function is used to load the value in DDL
}
} catch (Exception ex) {
}
}
加载值功能
private void LoadValues()
{
try {
DataSet SampleDs = YourDS; // Your dataset values from DB
if (!string.IsNullOrEmpty(SampleDs.Tables(0).Rows(0)("yourvalue").ToString)) {
CompaniesDropDownList.SelectedValue = SampleDs.Tables(0).Rows(0)("yourvalue").ToString; // assuming the data in the table is value of DDL
}
} catch (Exception ex) {
}
}