0

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>
4

3 回答 3

3

在 PageLoad 中设置 SelectedIndex 之前,需要先将数据绑定到 DropDownList

于 2013-10-10T08:42:36.523 回答
0

在您的 aspx 代码中,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);
            }
        }
    }
于 2013-10-10T08:56:50.417 回答
0

Para hacer que funcione el SelectIndex de un DropDownList en C#, hay que llamar el eventto de SelectIndexChanged de la 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);
        }
  }

萨鲁多斯!!

于 2015-01-07T18:17:42.510 回答