DropdownList.selectedIndex总是0(是的,我确实有!isPostBack)

(向下滚动到post底部以找到解决方案。)

有一个包含Datalist的asp.net页面。 在这个数据列表中,有一个包含下拉列表的模板,每次数据列表中都填充了一个项目,就会调用一个ItemCreatedCommand。 itemCreatedCommand负责数据绑定下拉列表。

我认为问题出在这里,我正在使用ItemCreatedCommand填充它 – 但奇怪的是,如果我选择颜色“绿色”,页面将自动回复,我会看到下拉列表仍然是绿色,但在尝试使用它的SelectedIndex时,我总是得到0 ……

protected void DataListProducts_ItemCreatedCommand(object source, DataListItemEventArgs e) var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex]; var item = itemBLL.GetFullItem(itemId); var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor"); //Also tried with : //if(!isPostBack) { DropDownListColor.DataSource = item.ColorList; DropDownList.Color.Databind(); // } End !isPostBack) Label1.test = DropDownListColor.SelectedIndex.toString(); // <- THIS IS ALWAYS 0! *grr* 

我已经缩小了代码以供查看,但是你仍然可以看到我正在尝试做什么:)之所以我这样做,而不是直接为aspx-page声明颜色的数据源,是因为我需要运行一个测试if(showColors),但是我不想把代码放在html页面上,我认为应该在代码后面的文件中。

编辑:在尝试改变SelectedIndexChange之后 – 我现在脑子里有一个“逻辑”混乱 – 我如何改变数据主义者内部的元素? 因为据我所知 – 我没有办法检查这个特定下拉列表属于的数据列表中的哪些项目……或者? 我将尝试一些方法,看看我最终得到了什么;)但请发表你对这个问题的看法:)

解:

要么将事件冒泡到ItemCommand,要么处理事件,获取发件人父级(这是一个datalistItem并操纵那里的元素)。

  protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e) { DropDownList dropDownListColor = (DropDownList)sender; DataListItem dataListItem = (DataListItem)dropDownListColor.Parent; var item = items[dataListItem.ItemIndex]; var color = item.ItemColor[dropDownListColor.SelectedIndex]; var LabelPrice = (Label)dataListItem.FindControl("LabelPrice"); LabelPrice.Text = color.Price; } 

当DataList是数据绑定时,尚未处理AutoPostBack,即ItemCreated事件中的值仍然是原始值。

您需要处理下拉控件的SelectedIndexChange事件。

关于你的第二个问题:

我建议你从下拉列表中删除AutoPostBack,添加一个“更新”按钮,并更新按钮Click事件中的数据。

该按钮可以保存Command和CommandArgument值,因此很容易与数据库记录关联。

谢谢你的解决方案

  protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) { try { ModalPopupExtender1.Show(); if (ViewState["Colors"] != null) { FillColors(ViewState["Colors"].ToString()); } DropDownList dropDownListColor = (DropDownList)sender; DataListItem dataListItem = (DataListItem)dropDownListColor.Parent; Image image = (Image)dataListItem.FindControl("mdlImage"); Label ProductCode = (Label)dataListItem.FindControl("lblprdCode"); Label ProductName = (Label)dataListItem.FindControl("lblProdName"); DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity"); Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice"); Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice"); //Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice"); } catch (Exception ex) { } }