我想根據DropDownList ddlMeals
中的選擇使用合適的值選擇DropDownList ddlMealType
中的正確選項。當我手動選擇膳食時,這可以正常工作,但在頁面最初加載時不起作用(因爲對於ddlMeal
,selectedIndex = -1)。在Page_Load中設置DropDownList.SelectedIndex
因此,我嘗試將選定的索引設置爲Page_Load中列表中的第一個Meal,但是在下一行添加斷點時,可以看到SelectedIndex的值仍然爲-1。 是不是可以編程設置dropdownList的SelectedIndex屬性?
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>