我正在尝试使用适当的值在DropDownList ddlMealType
中选择正确的选项,具体取决于DropDownList ddlMeals
中的选择。这在我手动选择Meal时工作正常,但在最初加载页面时却没有(因为ddlMeal
的selectedIndex = -1)。
因此我尝试将所选索引设置为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>
答案 0 :(得分:3)
在设置PageLoad中的SelectedIndex
之前,需要将数据绑定到DropDownList答案 1 :(得分: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);
}
}
}
答案 2 :(得分:0)
Para hacer que funcione el SelectedIndex de un DropDownList zh C#,hay que llamar el evento 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);
}
}
Saludos !!