I have a dropdown like this:
<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>
I am setting its selected value like this:
CompaniesDropDownList.SelectedItem.Value = "3";
and it is working.
after setting this value, I am checking in if condition, the selected index or value like this:
if (CompaniesDropDownList.SelectedValue == "0")
or
if (CompaniesDropDownList.SelectedIndex == 0)
and it is always true. Although in dropdownlist on front end, item with value 3 is selected.
How to get selected index of this dropdown ?
Please suggest
that is what i want. i want to get the value from db and set selected index on page load.
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) {
}
}
Load Values function
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) {
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.