I am trying to selet the correct choice in DropDownList ddlMealType
with the appropriate value depending on the selection in DropDownList ddlMeals
. This works fine when I manually select a Meal, but not when the page is originally loaded (since selectedIndex = -1 for ddlMeal
).
I therefore try to set the selected index to the first Meal in the list in Page_Load, but when adding a breakpoint on following row, I can see that the value of SelectedIndex is still -1. Is it not possible to programatically set the SelectedIndex property of a dropdownList?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlMeals.SelectedIndex = 0;
ddlMeals_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlMeals_SelectedIndexChanged(object sender, EventArgs e)
{
// Fetch details for selected Meal
SqlDataReader reader = null;
String ConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["Kunskapshjulet"].ConnectionString;
SqlConnection connection1 = new SqlConnection(ConnectString);
SqlCommand selectCommand = new SqlCommand("SELECT MealType FROM Meals WHERE MealID = " + ddlMeals.SelectedValue, connection1);
try
{
connection1.Open();
reader = selectCommand.ExecuteReader();
reader.Read();
string strMealtype = reader[0].ToString();
ddlMealTypes2.SelectedValue = reader[0].ToString();
}
<asp:DropDownList ID="ddlMeals" runat="server" OnSelectedIndexChanged="ddlMeals_SelectedIndexChanged"
AutoPostBack="True" DataSourceID="SqlMealsPerUser" DataTextField="MealName" DataValueField="MealID" Width="180px">
</asp:DropDownList>