2013-10-10 32 views
0

我想根據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> 

回答

3

您需要設置在pageLoad的

0

將selectedIndex在你的aspx代碼之前的數據DropDownList的綁定,SqlMealsPerUser是您的數據源ID。它有什麼價值嗎?我相信只有在Page_Load背後的代碼完成後,數據纔會綁定到控件。

在這種情況下,你可以使用

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      ddlMeals.DataSource=BindData(); // this function gets the data u need to bind to your drop down. 
      ddlMeals.DataBind(); 
      if(ddlMeals.Items.Count > 0) 
      { 
       ddlMeals.SelectedIndex = 0; 
       ddlMeals_SelectedIndexChanged(null, EventArgs.Empty); 
      } 
     } 
    } 
0

帕拉hacer闕funcione EL SelectIndex日聯合國DropDownList的EN C#,乾草闕llamar EL事件摘要德SelectIndexChanged德拉siguiente MANERA:

protected void Page_Load(object sender, EventArgs e) 
    { 
    if (!IsPostBack) 
    { 
     ddlMeals.DataBind(); 
     if(ddlMeals.Items.Count > 0) 
     { 
      ddlMeals.SelectedIndex = 0; 
      ddlMeals_SelectedIndexChanged(null, EventArgs.Empty); 
     } 
    } 

Saludos !

相關問題